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

2024-05-12 00:27:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根像“苹果”一样的绳子。我想找到这个字符串,我知道它存在于数百个文件中的一个。e、 g

file1
file2
file3
file4
file5
file6
...
file200

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

我想到了这个:

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

而这个:

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

Tags: 文件字符串in苹果appleforfile1grep
3条回答

假设这些文件都在同一个目录中,我们只得到一个当前目录列表。

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

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

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

当它找到目标字符串时,它会打印文件名。

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

为了简单起见,这假定您的文件位于当前目录中:

def whichFile(query):
    for root,dirs,files in os.walk('.'):
        for file in files:
            with open(file) as f:
                if query in f.read():
                    return file
for x in  os.listdir(path):
    with open(x) as f:
        if 'Apple' in f.read():
         #your work
        break

相关问题 更多 >