我有一个像“苹果”一样的字符串。我想找到这个字符串,并且我知道它存在于数百个文件中的一个中。例如
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
鉴于这些文件都位于同一目录中,我们只获得当前目录列表。
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
当我们完成(或发生异常)时它们也会自动关闭。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)