[英]How do I pull text from a specific text line in Python?
如何使用Python从文本文件内的特定文本行中提取文本?
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 following Python example should extract the correct line number, but it is horribly inefficient: 以下Python示例应提取正确的行号,但效率极低:
f = open('file.txt')
print f.readlines()[line_number]
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. 一种更有效的技术将取决于您的使用方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.