Python将文件中的字符串与目录中的多个文件进行比较



我已经完成了以下代码的部分工作,但最终我希望对照目录中的多个文件检查第一个文件(input.txt(,并在找到它时输出一个字符串和文件名(来自目录(。有什么建议吗?

f = open('out.txt', 'w')
filenames = ["input.txt", "compare.dat", "compare2.dat", "compare3.dat"]
files = [open(name) for name in filenames]
sets = [set(line.strip() for line in file) 
for file in files]
common = set.union(*sets)
my_list = list(common)
my_list.sort()
print (my_list)
for file in files: file.close()

for line in my_list:
if.write(line+'n')
if.close()

此解决方案可以工作:

def readB(x):
for name in filesnames:
with open(name) as resultFile:
for line in resultFile:
if x in line:
print x,name

def readA():
with open('A.txt') as bondNumberFile: ## instead of A.txt call the .txt file from which every other file has to be matched
for line in bondNumberFile:
readB(line.rstrip())
readA()

最新更新