我正在嘗試使用另一個檔案洗掉第一個給定檔案的內容。這是因為第一個檔案包含的資料也在第二個檔案中。但是,第二個檔案比第一個檔案包含更多和更新的資料。因此,我想從第二個檔案中洗掉第一個檔案的內容。
我試過這個:
# 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
uj5u.com熱心網友回復:
您正在嘗試迭代打開的檔案緩沖區。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://www.uj5u.com/caozuo/458907.html
標籤:Python python-3.x 文件 比较
下一篇:如何使用Pygithub追加檔案
