Python中用print方法向文件中写入内容

来源:互联网 发布:长江航运能力 知乎 编辑:程序博客网 时间:2024/05/21 07:55

http://www.yangyanxing.com/article/749.html

一个小功能,我就是想用print功能实现,不想用write

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

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

import osos.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,charexcept IOError as err:    print("Write error"+ str(err))

http://tieba.baidu.com/p/4427708271

在程序最前面加上这段

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