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
2010-03-15 01:15:05
You want `[33]` for the 34th line.
Alok
2010-03-15 01:19:39
@Alok Indeed. Updated, thanks.
tarn
2010-03-15 01:22:55
A:
There's two ways:
- Read the file, line by line, stop when you've gotten to the line you want
- 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
2010-03-15 01:20:52
+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
2010-03-15 01:21:35
+1 for a nice elegant solution and we (or at least I) learned something new.
Justin Ethier
2010-03-15 01:28:37
nice, but if other processing is needed on other lines, opening the file is still needed.
ghostdog74
2010-03-15 02:32:09
@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
2010-03-15 02:58:21
+1 you are a genius Alex. I learn at least `2` new things from you everyday :D
TheMachineCharmer
2010-03-15 03:02:37
@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
2010-03-15 03:47:23
A:
for linenum,line in enumerate(open("file")):
if linenum+1==34: print line.rstrip()
ghostdog74
2010-03-15 01:24:56
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
2010-03-15 03:44:07
+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
2010-03-15 02:32:29