1. 程式人生 > >Python中用print方法向檔案中寫入內容

Python中用print方法向檔案中寫入內容

一個小功能,我就是想用print功能實現,不想用write

import os
os.chdir("/usr/tem")
char="my name is yangyanxing"
f = open("test.txt","w")
print >>f,char

但是Python3中還可以用以下的方式

import os
os.chdir("/usr/tem")
char="my name is yangyanxing"
f = open("test.txt","w")
print(char,file=f)

也可以考慮用with as結構,會簡單與周全些

try:
    with("man.txt","w") as data:
        print >>data,char
except IOError as err:
    print("Write error"+ str(err))

在程式最前面加上這段

f_result=open('result.txt', 'w') 
sys.stdout=f_result
print 'print to file'