简体   繁体   English

从文件中读取特定行

[英]reading specific lines from a file

What's the best way of reading only the specific lines (based on matching text) from a file? 从文件中仅读取特定行(基于匹配文本)的最佳方法是什么? This is what I'm doing now: 这就是我现在正在做的:

match_txt = "lhcb"
for inFile in os.listdir('.'):
    readFile = open(inFile, 'r')
    lines = readFile.readlines()
    readFile.close()

    for line in lines:
        if line.find(match_txt)==0:
           #< do stuff here >

ie I'm reading the lines, only with "lhcb" in it, from all the files in the present directory one by one. 即我从当前目录中的所有文件中逐行读取行,仅带有“ lhcb”。 Is it the best way of doing that? 这是最好的方法吗? Can it be done without loading the whole file in the memory in the first place? 可以不先将整个文件加载到内存中就可以完成吗?

To do it without loading the whole file into memory, just iterate over the file: 为此,无需将整个文件加载到内存中,只需遍历该文件即可:

match_txt = "lhcb"
for file_name in os.listdir('.'):
    with open(file_name) as f:
        for line in f:
            if line.startswith(match_txt):
                #< do stuff here >

If you want to check for match_txt anywhere in the line, you can use 如果要在该行的任何地方检查match_txt ,可以使用

if match_txt in line:

Your example code is equivalent to checking if the line starts with match_txt though. 您的示例代码等效于检查行是否 match_txt

If you're using a very old version of Python that doesn't have the with statement, you'll have to close the file manually: 如果您使用的是非常老的Python版本,但没有with语句,则必须手动关闭文件:

match_txt = "lhcb"
for file_name in os.listdir('.'):
    f = open(file_name)
    for line in f:
        if line.startswith(match_txt):
            #< do stuff here >
    f.close()

You should look into the str.startswith() function. 您应该研究str.startswith()函数。

if line.startswith("text"):

http://docs.python.org/library/stdtypes.html#str.startswith http://docs.python.org/library/stdtypes.html#str.startswith

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM