How do I pull text from a specific text line in Python?
How would I pull text from a specific text line, inside a text file using Pyth开发者_如何转开发on?
If you want to read the 10th line:
with open("file.txt") as f:
for i in range(9):
f.next()
print f.readline()
This doesn't read the whole file in memory.
The simplest method:
print list( open('filename') )[line_number]
That's gonna read in the whole file which may not be a good idea. A more efficient technique would depend on how you are using it.
The following Python example should extract the correct line number, but it is horribly inefficient:
f = open('file.txt')
print f.readlines()[line_number]
精彩评论