在Python中查找包含所需字符串的文件中的一个文件

E.C*_*oss 3 python

我有一个像'苹果'的字符串.我想找到这个字符串,我知道它存在于数百个文件中的一个中.例如

file1
file2
file3
file4
file5
file6
...
file200
Run Code Online (Sandbox Code Playgroud)

所有这些文件都在同一目录中.使用python查找哪个文件包含此字符串的最佳方法是什么,知道只有一个文件包含它.

我想出了这个:

for file in os.listdir(directory):
    f = open(file)
    for line in f:
        if 'apple' in f:
            print "FOUND"
    f.close()
Run Code Online (Sandbox Code Playgroud)

还有这个:

grep = subprocess.Popen(['grep','-m1','apple',directory+'/file*'],stdout=subprocess.PIPE)
found = grep.communicate()[0]
print found
Run Code Online (Sandbox Code Playgroud)

Lev*_*von 8

鉴于文件都在同一目录中,我们只获取当前目录列表.

import os

for fname in os.listdir('.'):    # change directory as needed
    if os.path.isfile(fname):    # make sure it's a file, not a directory entry
        with open(fname) as f:   # open file
            for line in f:       # process line by line
                if 'apples' in line:    # search for string
                    print 'found string in file %s' %fname
                    break
Run Code Online (Sandbox Code Playgroud)

这会自动获取当前目录列表,并检查以确保任何给定条目是文件(而不是目录).

然后它打开文件并逐行读取(以避免内存问题,它不会立即读取它)并在每一行中查找目标字符串.

当它找到目标字符串时,它会输出文件的名称.

此外,由于文件是打开使用with它们也在我们完成时自动关闭(或发生异常).