Reading/Writing 到 Python 中的文件

Reading/Writing to a file in Python

我有一个 python 代码,上面有一些打印 statements.Now,我想从一个文件读取输入并将其输出到另一个文件 file.How 我要这样做吗? 我应该包括这个吗?

代码 :

fo = open("foo.txt", "r")
foo = open("out.txt","w")

您可以使用:

with open("foo.txt", "r") as fo, open("out.txt", "w") as foo:
    foo.write(fo.read())

天真的方式:

fo = open("foo.txt", "r")
foo = open("out.txt","w")
foo.write(fo.read())
fo.close()
foo.close()

更好的方法,使用 with:

with open("foo.txt", "r") as fo:
    with open("out.txt", "w") as foo:
        foo.write(fo.read())

不错的方法(使用为您完成的模块 - shutil.copy):

from shutil import copy
copy("foo.txt", "out.txt")