python - 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()
推荐阅读
- c++ - C ++:在另一个函数中声明一个函数不是编译器错误所以......它是什么?
- swift - 如何在右侧绘制类似于所示图像的带有 ARC 的 UIBezierPath?
- c# - C# 使用预定义的排序数组对数组进行排序
- c++ - 用于 OSX/Windows 编译的 Cmakelists.txt 问题
- python - 如何迭代熊猫数据框的集合?
- python - 将文件中的多行转换为元组和列表格式
- android - Android 设备没有响应
- javascript - 递增/递减时将整数限制为数组 indeces
- docker - 如何解决这个烦人的 docker 错误?(注册图层失败)
- spring - OAuth2Authentication.getPrincipal() 返回 client_id 而不是用户名