为什么这个 Python 代码不能将一个文件中的文本复制到另一个文件中?
Why isn't this Python code copying the text in one file to another?
所以,我正在尝试将一些文本从一个 .txt 文件复制到另一个文件。但是,当我打开第二个 .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()
method. 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))
所以,我正在尝试将一些文本从一个 .txt 文件复制到另一个文件。但是,当我打开第二个 .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()
method. 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))