[Tutor] reading 2nd line

Magnus Lycka magnus@thinkware.se
Mon Jan 27 04:35:02 2003


At 13:00 2003-01-27 +0530, Jayprasad J. Hegde wrote:
>I have attached a very simple code

I'd suggest pasting small snippets of code into the mail
body instead of making attachments. That makes life
easier for most of us.

>entries = myfile.read ().splitlines ()

This means that you read the entire file into a string, and then
split it into lines. A more convenient way to do that would be
to use myfile.readlines(), but it's still not a very good idea.
If we don't want more than the second line, there is no reason
to read past that. The file might be big... So I'd do:

filename = ...
myfile = file(filename)
myfile.readline() # Read first line and drop result
secondLine = myfile.readline()
myfile.close()

This will be much faster than to read a big file. Particularly
if we work with many files, as in:

import glob
closePos = 4

# Process close value in second line of all files
# with .csv extension in current folder.
for fn in glob.glob('*.csv'):
     f = file(fn)
     f.readline()
     line2 = f.readline()
     process(fn, line2.split(',')[closePos])
     f.close()

If we have 100 files with 100 lines each, we will now read 200
lines totally, instead of 10,000 lines if we had used .read()
or .readlines().

I assume the "process" function needs the file name as well as the
close value in this case to figure out what stock it was.


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se