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

时间:2018-11-26 07:50:43

标签: python file

我有下面的代码可以部分工作,但是最终我希望针对目录中的多个文件检查第一个文件(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()

1 个答案:

答案 0 :(得分:0)

此解决方案可能有效:

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