繁体   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