2014-07-17 20 views
0

通常,當我將stdout寫入文件時,我是這樣做的。將stdout寫入文件的更好方法

import sys 
sys.stdout = open(myfile, 'w') 
print "This is in a file." 

現在,這種方法看起來很醜,我聽說這裏和那裏有一個更好的方法。如果是這樣,這個更好的方法是什麼?

+4

很高興在StackOverflow,mr。主席。看到這個相關/重複的線程:http://stackoverflow.com/questions/4110891/python-how-to-simply-redirect-output-of-print-to-a-txt-file-with-a-new-line -crea – alecxe

回答

4

您還可以利用print實際上可以寫入文件的事實。

with open("file.txt", "w") as f: 
    print("Hello World!", file=fd) 

注:這是Python的3.x的語法只print是在Python 3.x的功能

對於Python 2.x的,你可以做不過:

from __future__ import print_function 

否則同樣可以實現:

with open("file.txt", "w") as fd: 
    print >> fd, "Hello World!" 

參見:print()從Python的3.x的文檔。

3

直接打印到文件,即使用

with open(myfile, 'w') as fh: 
    fh.write("This is in a file.\n") 

with open(myfile, 'w') as fh: 
    print >>fh, "This is in a file." 

from __future__ import print_function 
with open(myfile, 'w') as fh: 
    print("This is in a file.", file=fh) 
2

你可以做到這一點,如圖在其他的答案,但它那種得到舊的在每個語句中指定輸出文件。所以我明白只是重定向sys.stdout的衝動。但是,是的,你提出的做法並不盡如人意。添加適當的錯誤處理將使其更加醜陋。幸運的是,你可以創建一個方便的上下文管理來解決這些問題:

import sys, contextlib 

@contextlib.contextmanager 
def writing(filename, mode="w"): 
    with open(filename, mode) as outfile: 
     prev_stdout, sys.stdout = sys.stdout, outfile 
     yield prev_stdout 
     sys.stdout = prev_stdout 

用法:

with writing("filename.txt"): 
    print "This is going to the file" 
    print "In fact everything inside the with block is going to the file" 
print "This is going to the console." 

注意,您可以使用as關鍵字來獲取以前stdout,所以你仍然可以打印到with區塊內的屏幕:

with writing("filename.txt") as stdout: 
    print "This is going to the file" 
    print >> stdout, "This is going to the screen" 
    print "This is going to the file again"