【发布时间】:2019-08-23 05:55:43
【问题描述】:
我想比较两个文本文件。第一个文本文件中的行不在第二个文本文件中。我想复制这些行并将它们写入一个新的 txt 文件。我想要一个 Python 脚本,因为我经常这样做,并且不想经常上网查找这些新行。我不需要确认 file2 中是否有 file1 中没有的内容。
我编写了一些似乎运行不一致的代码。我不确定自己做错了什么。
newLines = open("file1.txt", "r")
originalLines = open("file2.txt", "r")
output = open("output.txt", "w")
lines1 = newLines.readlines()
lines2 = originalLines.readlines()
newLines.close()
originalLines.close()
duplicate = False
for line in lines1:
if line.isspace():
continue
for line2 in lines2:
if line == line2:
duplicate = True
break
if duplicate == False:
output.write(line)
else:
duplicate = False
output.close()
对于file1.txt:
Man
Dog
Axe
Cat
Potato
Farmer
file2.txt:
Man
Dog
Axe
Cat
output.txt 应该是:
Potato
Farmer
但实际上是这样的:
Cat
Potato
Farmer
任何帮助将不胜感激!
【问题讨论】:
-
如果您使用的是 Linux/Unix 操作系统,最好的命令(不是 Python)是
comm -23 file1.txt file2.txt。
标签: python file text readlines