[rust-dev] read file line by line

Mohd. Bilal Husain bilal at bilalhusain.com
Tue Apr 3 09:21:23 PDT 2012


Although I have doubts about IndexError in the python code, you can
possibly check empty line by testing the string length.

You can use str::len to get the string length

    str::len(line) == 0u

split using str::split_char

    let parts = str::split_char(line, '\t');

and iterate on parts

    for part in parts {
        /* ... */
    }

Use str::trim for trimming unicode space characters and cont keyword* to
continue the loop.

Also, in case you are benchmarking Rust vs Python code for text processing,
can you post your results and if you liked writing Rust code :)

* http://doc.rust-lang.org/doc/tutorial.html#loops

On 3 April 2012 19:24, Mic <mictadlo at gmail.com> wrote:

> Thank you. How to check whether the last line is not empty?
> Because line.split_char('\t') would not make sense to run on an empty line.
>
> In python I did it in the following way:
>         with open(args.output, 'r') as outfile:
>             for line in infile:
>                 try:
>                     parts = [part.strip() for part in line.split('\t')]
>                 except IndexError:
>                     continue
>
> On Tue, Apr 3, 2012 at 8:36 PM, Mohd. Bilal Husain <bilal at bilalhusain.com>wrote:
>
>> As you figured out, the function read_line can be used from the
>> reader_util implementation from module io
>>
>> ~~~~
>>
>> import io::reader_util;
>>
>> #[doc = "reads the entire file line by line except the first line"]
>> fn main(args: [str]) {
>>     if args.len() == 1u {
>>         fail #fmt("usage: %s <filename>", args[0]);
>>     }
>>
>>     let r = io::file_reader(args[1]); // r is result<reader, err_str>
>>     if result::failure(r) {
>>         fail result::get_err(r);
>>     }
>>
>>     let rdr = result::get(r);
>>     rdr.read_line(); // skip line
>>     while !rdr.eof() {
>>         io::println(rdr.read_line());
>>     }
>> }
>> ~~~~
>>
>> I don't think Rust lets you catch exceptions while reading the stream as
>> you can't do much about it*.
>>
>> * Error handling in Rust is unrecoverable unwinding
>>
>> On 3 April 2012 13:34, Mic <mictadlo at gmail.com> wrote:
>>
>>> Hello,
>>> I found read_line, but I do not how to convert the following Python code
>>> (skip first line and print all other lines from a file) to Rust.
>>>
>>> f = open(file_name, 'r')
>>> f.next()                        #skip line
>>> for line in f:
>>>     print line
>>> f.close()
>>>
>>> How rust handle exceptions?
>>>
>>> Thank you in advance.
>>>
>>> _______________________________________________
>>> Rust-dev mailing list
>>> Rust-dev at mozilla.org
>>> https://mail.mozilla.org/listinfo/rust-dev
>>>
>>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20120403/a95d668c/attachment-0001.html>


More information about the Rust-dev mailing list