为什么不是';难道这不是将一个文件中的文本复制到另一个文件中的Python代码吗?

为什么不是';难道这不是将一个文件中的文本复制到另一个文件中的Python代码吗?,python,io,text-files,Python,Io,Text Files,因此,我试图将一些文本从一个.txt文件复制到另一个。但是,当我打开第二个.txt文件时,程序并没有在其中写入行。这是我正在使用的代码 chptfile = open('v1.txt',"a+",encoding="utf-8") chptfile.truncate(0) chptfile.write("nee\n") chptfile.write("een") lines = chptfile.readlines

因此,我试图将一些文本从一个.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的回答中一样,您需要调用该方法。然而,代码中也有一个不好的做法。使用以下命令代替打开和关闭文件:

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