简体   繁体   English

如何从Python中的特定文本行中提取文本?

[英]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.

相关问题 如何从 python 中的文本文件中删除特定行 - How do I remove a specific line from a text file in python Python:如何从特定的文本行中获取字数并保存以对其进行计算 - Python: How do I get the word count from a specific line of text and save it to do calculations on it 如何从Python Requests / Beautiful Soup中的某些文本参数获取HTML的特定行 - How do I get specific line of HTML from certain text parameter in Python Requests/Beautiful Soup 如何从文本文件中提取特定信息? Python - How do you pull specific information out of a text file? Python 我如何从 python 中的特定行读取文本文件? - How i can Read text file from a specific line in python? 我想通过 python 从文本文件中提取特定数据 - I want to pull specific data from a text file through python 如何使用python编辑文本文件中的特定行而不将文本文件中的所有内容转换为列表? - How do I edit a specific line in a text file with python without converting everything in the text file into a list? 在python中编辑一行文本时,如何避免在引号中编辑文本的特定部分? - While editing a line of text in python, how do i avoid editing a specific part of text in quotation marks? 如何从python中的文本文件中切出一行? - How do I slice a line from a text file in python? 如何使用python从文本文件中复制特定字符串? - How do I copy specific strings from a text file with python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM