我有一些带有一些print语句的python代码。现在,我想从一个文件中读取输入并将其输出到另一个文件。我该怎么办? 我应该包括这个吗?
代码:
fo = open("foo.txt", "r")
foo = open("out.txt","w")
答案 0 :(得分:1)
您可以使用:
with open("foo.txt", "r") as fo, open("out.txt", "w") as foo:
foo.write(fo.read())
答案 1 :(得分:1)
朴素的方式:
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")