2011-06-24 22 views
2

我的代码:指定数据文件对象在Python

out=open('ab.txt','w') 
print("Norwegian Blues stun easily.", file=out) 

当我在"file=out"这样它给语法错误在第二行 该怎么做,请帮助

感谢

+1

Python 3使用“python3”运行。 “python”运行Python 2. –

回答

0

忽略你确切的问题,你不介意做这样的事情:

out_file = open("test.txt", "wt") 
out_file.write("This Text is going to out file\nLook at it and see!") 
out_file.close() 

我发现here

编辑: 另外,该代码段是沿无论你在做什么线条更:

with open('out.log', mode='w', encoding='utf-8') as a_file, RedirectStdoutTo(a_file): 
    print('B') 

我发现THAT within this page

EDIT2: 好吧,这可能是更有益的(from here):

#stdout.py 
import sys 

print 'Dive in'           
saveout = sys.stdout          
fsock = open('out.log', 'w')        
sys.stdout = fsock          
print 'This message will be logged instead of displayed' 
sys.stdout = saveout          
fsock.close()    
2

您是否已经验证,这是不小心在Python的早期版本上运行,就像为运行不同版本的结果并排侧?此语法在3.x之前不可用。如果你从解释器中执行这一点,应该提到它运行的是哪个版本,在启动时,你也应该能够运行命令(解释外)

蟒蛇--version

看系统默认的是什么。

+0

不需要验证,这是毫无疑问的问题。 :-) –