我试图用另一个文件删除第一个给定文件的内容。这是因为第一个文件包含的数据也在第二个文件中。但是,第二个文件比第一个文件包含更多和更新的数据。因此,我要从第二个文件中删除第一个文件的内容。
我试过这个:
# file 1 needs to be compared with file 2
with open(path8 + "recent.txt") as timelog:
lines = timelog.read()
time = lines.split('\n', 1)[0]
print(time)
# file 1
finold = open(path7 + time + 'temp.csv', 'r')
# file 2
finnew = open(pathmain + "file2.csv", 'r')
copyfinnew = open(path7 + "tempfile1.csv", 'w')
fout = open(path7 + "tempfile2.csv", 'w')
for line in finnew:
copyfinnew.write(line)
lines = line
delete = lines.split('\n', 1)[0]
if not delete in finold:
print(delete, " not in finold")
fout.write(delete + '\n')文件1是一个“日志”文件,它是在上次运行主代码(而不是这个)时自动保存的。文件2是尚未通过主代码运行的新文件,但需要将文件1的内容与其分离,以便主代码具有较少的数据可供运行。
错误似乎是,“如果没有删除在finold:”没有做我预期它做的事情。我想看看文件2中的字符串是否存在于文件1中。它看起来确实循环正确,但是它返回了文件2中的所有字符串。我已经给出了下面的例子。
我希望这是有意义的,我希望有人有答案。
finold的样本如下:
Srno,Flex Mood,Montana,08 Apr 2022 00:02
and for finnew it would be:
Bryan Mg,Bryan,Ça Sert à Rien,08 Apr 2022 00:11
Glowinthedark,Lituatie,Anders,08 Apr 2022 00:08
Architrackz,Perfecte Timing,Oh Baby (Whine),08 Apr 2022 00:05
Srno,Flex Mood,Montana,08 Apr 2022 00:02
that means that an example of fout would be:
Bryan Mg,Bryan,Ça Sert à Rien,08 Apr 2022 00:11
Glowinthedark,Lituatie,Anders,08 Apr 2022 00:08发布于 2022-04-17 05:05:33
您正在尝试迭代打开的文件缓冲区。如果要迭代每一行,则需要读取它们并将它们拆分为行,就像在使用timelog的第一个代码块中那样。
就像这样:
# file 1
finold = open(path7 + time + 'temp.csv').read().split("\n")
# file 2
finnew = open(pathmain + "file2.csv").read().split("\n")
copyfinnew = open(path7 + "tempfile1.csv", 'w')
fout = open(path7 + "tempfile2.csv", 'w')
for line in finnew:
copyfinnew.write(line)
if line not in finold:
print(line, " not in finold")
fout.write(line + '\n')https://stackoverflow.com/questions/71899352
复制相似问题