首页 > 解决方案 > 如何在 python 中将一个文件的内容复制到另一个文件?-我还包括了我失败尝试的代码

问题描述

例如在这里我试图将 file1 的内容移动到文件 2 中;这是我尝试的代码,它不起作用。我的代码有什么问题,有没有更有效的方法?

file1 = open("textfile.txt", "r")
file2 = open("second textfile.txt","w")
lines = file1.readlines()
for i in range(len(lines)):
    file2.write(lines[i]+"\n")

这个问题与其他类似类型的问题不同 - 因为它的解决方案特定于 python 中的编码。

标签: python

解决方案


如果要将一个文件的内容复制到另一个文件中,可以这样做:

firstfile = "textfile.txt"
secondfile = "second textfile.txt"

with open(firstfile, "r") as file:
    content = file.read()
    file.close()
    with open(secondfile, "w") as target:
        target.write(content)
        target.close()

推荐阅读