簡體   English   中英

用Python讀/寫文件

[英]Reading/Writing to a file in Python

我有一個帶有一些打印語句的python代碼。現在,我想從一個文件中讀取輸入並將其輸出到另一個文件中,我該怎么做? 我應該包括這個嗎?

代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM