2011-06-24 26 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

不需要驗證,這是毫無疑問的問題。 :-) –