在文件比较期间删除行而不删除行号或插入新的空行
Delete lines during file compare without deleting line numbers or injecting new blank lines
file2 有很多数字。 File1 有一个小的数字列表。 file2 与 file1 中的某些数字重复。我想从 file1 中删除 file2 中的重复数字而不删除 file2 中的任何数据,但同时不删除 file1 中的行号。我使用 PyCharm IDE 并分配行号。此代码确实删除了 file1 中的重复数据,但没有删除 file2 中的数据。这就是我想要的,但是它删除了重复的数字和行并在 file1 中重新写入它们,这是我不想做的。
import fileinput
# small file2
with open('file2.txt') as fin:
exclude = set(line.rstrip() for line in fin)
# big file1
for line in fileinput.input('file1.txt', inplace=True):
if line.rstrip() not in exclude:
print(line)
示例:正在发生的事情,file2 34344
file-1 开头:
54545
34344
23232
78787
file-1 结尾:
54545
23232
78787
我想要的
file-1 开始:
54545
34344
23232
78787
file-1 结尾:
54545
23232
78787
当您找到 exclude
集合中的数据时,您只需要打印一个空行。
import fileinput
# small file2
with open('file2.txt') as fin:
exclude = set(line.rstrip() for line in fin)
# big file1
for line in fileinput.input('file1.txt', inplace=True):
if line.rstrip() not in exclude:
print(line, end='')
else:
print('')
如果file1.txt是:
54545
1313
23232
13551
而file2.txt是:
1313
13551
运行之后file1.txt之前的脚本变成:
54545
23232
效率小记
如您所说,这段代码实际上是重写了所有行,包括编辑过的和未编辑过的。只删除和重写文件中间的几行并不容易,无论如何我不确定它对你的情况是否更有效率,因为你不知道 a priori应编辑哪些行:您始终需要逐行阅读和处理完整文件,以了解应编辑哪些行。据我所知,您很难找到比这个更有效的解决方案。如果有人知道怎么做,很高兴被拒绝。
file2 有很多数字。 File1 有一个小的数字列表。 file2 与 file1 中的某些数字重复。我想从 file1 中删除 file2 中的重复数字而不删除 file2 中的任何数据,但同时不删除 file1 中的行号。我使用 PyCharm IDE 并分配行号。此代码确实删除了 file1 中的重复数据,但没有删除 file2 中的数据。这就是我想要的,但是它删除了重复的数字和行并在 file1 中重新写入它们,这是我不想做的。
import fileinput
# small file2
with open('file2.txt') as fin:
exclude = set(line.rstrip() for line in fin)
# big file1
for line in fileinput.input('file1.txt', inplace=True):
if line.rstrip() not in exclude:
print(line)
示例:正在发生的事情,file2 34344
file-1 开头:
54545
34344
23232
78787
file-1 结尾:
54545
23232
78787
我想要的
file-1 开始:
54545
34344
23232
78787
file-1 结尾:
54545
23232
78787
当您找到 exclude
集合中的数据时,您只需要打印一个空行。
import fileinput
# small file2
with open('file2.txt') as fin:
exclude = set(line.rstrip() for line in fin)
# big file1
for line in fileinput.input('file1.txt', inplace=True):
if line.rstrip() not in exclude:
print(line, end='')
else:
print('')
如果file1.txt是:
54545
1313
23232
13551
而file2.txt是:
1313
13551
运行之后file1.txt之前的脚本变成:
54545
23232
效率小记
如您所说,这段代码实际上是重写了所有行,包括编辑过的和未编辑过的。只删除和重写文件中间的几行并不容易,无论如何我不确定它对你的情况是否更有效率,因为你不知道 a priori应编辑哪些行:您始终需要逐行阅读和处理完整文件,以了解应编辑哪些行。据我所知,您很难找到比这个更有效的解决方案。如果有人知道怎么做,很高兴被拒绝。