【问题标题】:Why isn't this Python code copying the text in one file to another?为什么这段 Python 代码不将一个文件中的文本复制到另一个文件中?
【发布时间】:2020-07-11 02:44:54
【问题描述】:

所以,我试图将一些文本从一个 .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()

【问题讨论】:

    标签: python io text-files


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      就像在 blhsing 的回答中一样,您需要调用 seek() 方法。但是,您的代码中也有一个不好的做法。不要打开和关闭文件,而是使用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))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-26
        • 2014-12-05
        • 1970-01-01
        • 1970-01-01
        • 2013-04-26
        • 2021-09-02
        • 1970-01-01
        相关资源
        最近更新 更多