首页 > 解决方案 > 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()

标签: pythonfile

解决方案


该解决方案可以工作:

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()

推荐阅读