简体   繁体   English

为什么这个 Python 代码不能将一个文件中的文本复制到另一个文件?

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

So,I am attempting to copy some text from one.txt file to another.所以,我试图将一些文本从一个.txt 文件复制到另一个。 However,when I open the second.txt file,the lines have not been written there by the program.但是,当我打开 second.txt 文件时,程序并没有在其中写入这些行。 This is the code that I'm using.这是我正在使用的代码。

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()

The file pointer of chptfile is at the end of the file after you perform the writes, so you should call the seek method to move the file pointer back to the beginning of the file before you can read its content: 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()
...

Like in blhsing's answer, you need to call the seek() method.就像在 blhsing 的回答中一样,您需要调用seek()方法。 However, there is also a bad practice in you code.但是,您的代码中也有一个不好的做法。 Instead of opening and closing a file, use a context manager :不要打开和关闭文件,而是使用上下文管理器

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