Python 2.7 Python文件匹配
目前有一个小任务,我有两个.txt文件,我想找到两个文件中出现的任何匹配的单词,并将结果输出到一个新文件,但是下面的代码只显示空白文件,不知道我需要更改或查看什么Python 2.7 Python文件匹配,python-2.7,Python 2.7,目前有一个小任务,我有两个.txt文件,我想找到两个文件中出现的任何匹配的单词,并将结果输出到一个新文件,但是下面的代码只显示空白文件,不知道我需要更改或查看什么 file1 example file2 example 12345 565 543252 54321 ff df 12345 0000 ff f0 11111 理想情况下,由于12345在两个文件中都匹配,因此应将file1中的12345 565行打印到输出文件中 with open(
file1 example file2 example
12345 565 543252
54321 ff df 12345
0000 ff f0 11111
理想情况下,由于12345在两个文件中都匹配,因此应将file1中的12345 565行打印到输出文件中
with open('Results.txt', 'r') as file1:
with open('test.txt', 'r') as file2:
same = set(file1).intersection(file2)
same.discard('\n')
with open('matches.txt', 'w') as file_out:
for line in same:
file_out.write(line)
任何帮助都将不胜感激。您的代码的问题在于
文件1的第一行实际上是:
12345 565
文件2的第二行是:
12345
您的代码将无法工作,因为intersect
将尝试匹配此不同的行
您可以做的是:
with open('Results.txt', 'r') as file1:
with open('test.txt', 'r') as file2:
a = set(x.split()[0] for x in file1)
b = [x.rstrip() for x in file2]
same = a.intersection(b)
same.discard('\n')
print same
输出:set(['12345'])
请注意,此方法仅使用file1
中的第一列,因此与其他列的任何其他匹配都不起作用。希望这有帮助非常感谢,效果非常好!出于兴趣,是否可以打印文件1中的整行?i、 e.12345565?