簡體   English   中英

為什么這個 Python 代碼不能將一個文件中的文本復制到另一個文件?

[英]Why isn't this Python code copying the text in one file to another?

所以,我試圖將一些文本從一個.txt 文件復制到另一個。 但是,當我打開 second.txt 文件時,程序並沒有在其中寫入這些行。 這是我正在使用的代碼。

chptfile = open('v1.txt',"a+",encoding="utf-8")
chptfile.truncate(0)
chptfile.write("nee\n")
chptfile.write("een")

lines = chptfile.readlines()
chptv2 = open ('v2.txt',"a+",encoding="utf-8")
for line in lines:
    chptv2.write(line)

chptv2.close()
chptfile.close()

chptfile的文件指針在您執行寫入后位於文件末尾,因此您應該調用seek方法將文件指針移回文件開頭,然后才能讀取其內容:

chptfile = open('v1.txt',"a+",encoding="utf-8")
chptfile.truncate(0)
chptfile.write("nee\n")
chptfile.write("een")
chptfile.seek(0)
lines = chptfile.readlines()
...

就像在 blhsing 的回答中一樣,您需要調用seek()方法。 但是,您的代碼中也有一個不好的做法。 不要打開和關閉文件,而是使用上下文管理器

with open('v1.txt',"a+",encoding="utf-8") as chptfile:
    chptfile.truncate(0)
    chptfile.write("nee\n")
    chptfile.write("een")
    chptfile.seek(0)
    lines = chptfile.readlines()

with open ('v2.txt',"a+",encoding="utf-8") as chptv2:
    chptv2.write(''.join(line))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM