[Tutor] printing a word in the second line of a text file
Jeff Shannon
jeff@ccvcorp.com
Thu, 18 Oct 2001 09:44:36 -0700
> tonycervone <tonycervone@netzero.net> asked:
>
> ... How about if I want to print a
> word according to any location in the second line of a text? ...
>
> and Remco Gerlich <scarblac@pino.selwerd.nl> replied:
>
> inp.readlines() returns a list of lines. split() is something you can do on
> an individual line. So you're almost there.
>
> What you wanted is read a single line, the first one. that's readline, not
> readlines.
>
> inp = open('filename')
> line = inp.readline()
> print line.split()[position]
>
> If you want to use readlines, it's read
>
> inp = open('filename')
> lines = inp.readlines()
> print lines[0].split()[position]
>
Now, in order to read a word from the second line, or whatever line number you want... you can do this in one of two ways:
---- example 1 ------
lineno = 2 # this is the line you want to read a word from...
inp = open('filename')
for n in range(lineno): #loop through this a number of times equal to lineno ...
line = inp.readline() # reading a single line (lineno times)
print line.split()[position]
---- example 2 ------
inp = open('filename')
lines = inp.readlines() # read in the entire file
myline = lines[lineno - 1] # grab the line we're interested in
print myline.split()[position]
-----------------------
Note that in example 2, when I go to grab the line I want, I use (lineno - 1)--this is because lists use 0-based indexing, instead of the 1-based counting that humans normally use (and yes, there *are* good reasons for this, but I won't go into them here). Example 1 uses a fairly slow loop-and-read process, while example 2 reads the entire file in one
gulp. As a result, example 2 will be quicker and probably more efficient for small files, or files that you want to look near the *end* of. Example 1 will be better for reading lines near the beginning of large files. Of course, exactly what "small" and "large" means, will depend on your processor, available memory, disk, etc... ;) (I'd use example 2
in strong preference to example 1, unless you're always grabbing from the first line or two, or are *very* short on memory... )
Jeff Shannon
Technician/Programmer
Credit International