2015-01-09 180 views
1

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

代碼

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

不,你應該使用情況管理器; '打開(「foo.txt」)爲fo,打開(「out.txt」,「w」)爲foo:' – jonrsharpe 2015-01-09 21:13:22

+0

您應該閱讀一些關於python編程的教程。但作爲開始,請查看[shutil](https://docs.python.org/2/library/shutil.html)。 – tdelaney 2015-01-09 21:13:24

+0

使用foo.write()打印出out.txt? @jonrsharpe – hvardhan 2015-01-09 21:16:20

回答

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

您可以使用:

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