在文件中查找目录中的文件名
我想确认我的程序是否记录了某种类型的所有文件。简单来说,我有一个日志文件,里面只有文件名,然后我用一个函数去检查这些文件是否存在。可是文件内容非常庞大,我的做法比较粗糙。结果不太奏效。
import subprocess
import sys
import signal
import shutil
import os, fnmatch
#open file to read
f=open("logs", "r") #files are stored in this directory
o=open("all_output_logs","w")
e=open("missing_logs",'w')
def locate(pattern, root=os.curdir):
'''Locate all files matching supplied filename pattern in and below
supplied root directory.'''
#ignore directories- ignore works, just uncomment.
#ignored = ["0201", "0306"]
for path, dirs, files in os.walk(os.path.abspath(root)):
#for dir in ignored:
# if dir in dirs:
#dirs.remove(dir)
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
#here i log all the files in the output file to search in
for line in f:
if line.startswith("D:"):
filename = line
#print line
o.write(filename)
f.close()
o.close()
r.close()
i=open("all_output_logs","r")
#primitive search.. going through each file in the directory to see if its there in the log file
for filename in locate("*.dll"):
for line in i:
if filename in i:
count=count+1
print count
else:
e.write(filename)
我发现我的计数变量没有被打印出来,而且我只得到了一个文件名,那个文件名居然是在列表的中间。
1 个回答
1
问题在于,文件中的内容只能在第一次读取时获取,而文件对象(在你的例子中是i
)并不支持你想要的那种in
操作。你可以把代码改成这样:
lines = open("all_output_logs","r").readlines()
for filename in locate("*.dll"):
for line in lines:
if filename in line:
count=count+1
print count
else:
e.write(filename)
不过这样做还是会比较低效,而且有点别扭。
因为你提到日志文件是"巨大的",所以你可能不想把它全部读入内存,这样的话你每次查找时就得回到文件开头:
f = open("all_output_logs","r")
for filename in locate("*.dll"):
f.seek(0)
for line in f:
if filename in line:
count=count+1
print count
else:
e.write(filename)
我保留了in
操作,因为你没有说明日志文件的每一行包含什么。一般来说,filename == line.strip()
应该是正确的比较方式。