tags:

views:

613

answers:

5

i want to go to line 34 in a .txt file and read it how would you do that? In python?

+1  A: 

You could just read all the lines and index the line your after.

line = open('filename').readlines()[33]
tarn
You want `[33]` for the 34th line.
Alok
@Alok Indeed. Updated, thanks.
tarn
A: 

There's two ways:

  1. Read the file, line by line, stop when you've gotten to the line you want
  2. Use f.readlines() which will read the entire file into memory, and return it as a list of lines, then extract the 34th item from that list.

Solution 1

Benefit: You only keep, in memory, the specific line you want.

code:

for i in xrange(34):
    line = f.readline();
# when you get here, line will be the 34th line, or None, if there wasn't
# enough lines in the file

Solution 2

Benefit: Much less code
Downside: Reads the entire file into memory
Problem: Will crash if less than 34 elements are present in the list, needs error handling

line = f.readlines()[33]
Lasse V. Karlsen
+16  A: 

Use Python Standard Library's linecache module:

line = linecache.getline(thefilename, 33)

should do exactly what you want. You don't even need to open the file -- linecache does it all for you!

Alex Martelli
+1 for a nice elegant solution and we (or at least I) learned something new.
Justin Ethier
@Justin, glad you liked it!
Alex Martelli
nice, but if other processing is needed on other lines, opening the file is still needed.
ghostdog74
@ghostdog, if the "processing" is on specifically numbered lines, just keep using `linecache` -- as the name implies, it caches things for you. A weird mix where some lines are accessed as numbered and others need looping on can be handled in different ways, but such weird mixes are hardly a common use case.
Alex Martelli
+1 you are a genius Alex. I learn at least `2` new things from you everyday :D
TheMachineCharmer
@MachineCharmer, heh, flattery will get you anywhere;-).
Alex Martelli
@alex, what i actually mean is, beside processing those specific line numbers, OP may want to use the other lines as well, maybe to output to some files etc etc..... Of course, this is not in OP's question, but just a thought.
ghostdog74
A: 
for linenum,line in enumerate(open("file")):
    if linenum+1==34: print line.rstrip()
ghostdog74
and if there are many lines in the file?
John Machin
don't understand. what many lines? if OP wants to stop at line 34, just do a break. Its still better than reading the whole file into memory.
ghostdog74
+1  A: 

A solution that will not read more of the file than necessary is from itertools import islice

line_number = 34

with open(filename) as f:
    # Adjust index since Python/islice indexes from 0 and the first 
    # line of a file is line 1
    line = next(islice(f, line_number - 1, line_number))

A very straightforward solution is

line_number = 34

with open(filename) as f:
    f.readlines()[line_number - 1]
Mike Graham