[Tutor] reading 2nd line

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun Jan 26 15:49:02 2003


On Sun, 26 Jan 2003, Jens Kubieziel wrote:

> I have here several text files, where I want to read second line of each
> file and no idea how to do it. Those files are csv-files exported from
> MS Excel and have following format:
>
>     date,open,high,low,close,sales
>     01-01-03,11.23,11.24,10.66,10.87,678537
>
> On a shell I would write:
>     head -n 2 $FILE | tail -n 1
>
> Can you give me a hint on this?

Hi Jens,

Yes, you may want to look at the function 'open()', which gives us a file
object, as well as the 'readline()' method of a file object:

    http://www.python.org/doc/lib/built-in-funcs.html#l2h-44
    http://www.python.org/doc/lib/bltin-file-objects.html#l2h-165

These two tools should allow you to get the second line of a file.



> If I read those line, I want to read out the close price (10.87). My
> current solution looks like:
>
> >>> line = "01-01-03,11.23,11.24,10.66,10.87,678537"
> >>> single = line.split(",")
> >>> print single[4]
>
> Is there a better solution?

For simple files, string splitting will work.  However, there is a
specialized third-party Python module that does CSV files:

    http://www.object-craft.com.au/projects/csv/

which handles subtleties like having commas within fields; you may want to
use this in favor of simple string splitting.


Good luck to you!