我想比较两个文本文件。第一个文本文件中的行不在第二个文本文件中。我想复制这些行并将它们写入一个新的txt文件。我想为这个Python脚本,因为我这样做了很多,不想去网上不断找到这些新行。如果文件2中有不在文件1中的内容,我不需要确认。你知道吗
我写了一些代码,似乎工作不一致。我不确定我做错了什么。你知道吗
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
文件2.txt:
Man
Dog
Axe
Cat
那个输出.txt应该是:
Potato
Farmer
但事实是:
Cat
Potato
Farmer
任何帮助都将不胜感激!你知道吗
您可以使用numpy实现更小更快的解决方案。 这里我们使用这些numpy方法 np.loadtxt文件文档:https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.htmlnp.setdiff1d设置文档:https://docs.scipy.org/doc/numpy-1.14.5/reference/generated/numpy.setdiff1d.htmlnp.savetxt文件文档:https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html
基于行为,
file2.txt
不会以换行符结尾,因此lines2
的内容是['Man\n', 'Dog\n', 'Axe\n', 'Cat']
。注意'Cat'
缺少换行符。你知道吗我建议你规范化你的台词,这样他们就不会有新词了,换成:
使用:
和变化:
收件人:
这将为您添加新行。实际上,最好的解决方案是完全避免内部循环,改变所有这些:
只是:
如果像我建议的那样使用
set
来表示lines2
,那么测试的开销将从file2.txt
中的线性行数下降到大致恒定的值,而不管file2.txt
的大小(只要唯一行的集合可以完全放入内存中)。你知道吗更好的方法是,对打开的文件使用
with
语句,并流式处理file1.txt
,而不是将其保存在内存中,最终得到:相关问题 更多 >
编程相关推荐