python - 如何从第一个文本文件中写入第二个文本文件中不存在的行?
问题描述
我想比较两个文本文件。第一个文本文件中的行不在第二个文本文件中。我想复制这些行并将它们写入一个新的 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
output.txt 应该是:
Potato
Farmer
但它是这样的:
Cat
Potato
Farmer
任何帮助将非常感激!
解决方案
基于行为,file2.txt
不以换行符结尾,所以内容lines2
是['Man\n', 'Dog\n', 'Axe\n', 'Cat']
. 请注意缺少换行符'Cat'
。
我建议规范化你的行,这样它们就没有换行符,替换:
lines1 = newLines.readlines()
lines2 = originalLines.readlines()
和:
lines1 = [line.rstrip('\n') for line in newLines]
# Set comprehension makes lookup cheaper and dedupes
lines2 = {line.rstrip('\n') for line in originalLines}
并改变:
output.write(line)
至:
print(line, file=output)
这将为您添加换行符。确实,最好的解决方案是完全避免内部循环,改变所有这些:
for line2 in lines2:
if line == line2:
duplicate = True
break
if duplicate == False:
output.write(line)
else:
duplicate = False
只是:
if line not in lines2:
print(line, file=output)
如果您按照我的建议使用set
for ,则无论大小如何lines2
,测试的成本都会从行数的线性下降到大致恒定(只要唯一行的集合完全可以放入内存) .file2.txt
file2.txt
更好的是,with
对打开的文件使用语句,并流式传输file1.txt
而不是将其保存在内存中,最终得到:
with open("file2.txt") as origlines:
lines2 = {line.rstrip('\n') for line in origlines}
with open("file1.txt") as newlines, open("output.txt", "w") as output:
for line in newlines:
line = line.rstrip('\n')
if not line.isspace() and line not in lines2:
print(line, file=output)
推荐阅读
- data-structures - 显示通用树并查找其中节点总数的时间复杂度
- python - 将字典转换为数据框,然后将列融合/堆叠为行
- swift - 使用 Double 初始化 Integer 时出现意外的 nil
- javascript - 如何在 React 中正确操作单选输入元素中的选中属性
- android - 使用textview android填写webview表单
- c++ - 如何在调试器中输入命令行输入来编程,以便能够观察每个步骤的输入发生了什么?
- algorithm - 多链接记录作为树的搜索思路
- mysql - Mysql如何授予多个数据库中存在的特定表的权限?
- angular - NativeScript 主题 - 将其设置为灯光模式
- php - 在 PHP 数组中查找相同的键值并将它们保存到具有更新值的输出数组中