-1
假設我寫stdout
到一個文件中,就像這樣:關閉與標準輸出文件被寫入到它
sys.stdout = open("file.txt", "w")
# print stuff here
這樣做行不通:
sys.stdout.close()
我怎樣才能關閉文件寫完stdout
後呢?
假設我寫stdout
到一個文件中,就像這樣:關閉與標準輸出文件被寫入到它
sys.stdout = open("file.txt", "w")
# print stuff here
這樣做行不通:
sys.stdout.close()
我怎樣才能關閉文件寫完stdout
後呢?
我將您的問題表示爲:「我如何將sys.stdout
重定向到文件?」
import sys
# we need this to restore our sys.stdout later on
org_stdout = sys.stdout
# we open a file
f = open("test.txt", "w")
# we redirect standard out to the file
sys.stdout = f
# now everything that would normally go to stdout
# now will be written to "test.txt"
print "Hello world!\n"
# we have no output because our print statement is redirected to "test.txt"!
# now we redirect the original stdout to sys.stdout
# to make our program behave normal again
sys.stdout = org_stdout
# we close the file
f.close()
print "Now this prints to the screen again!"
# output "Now this prints to the screen again!"
# we check our file
with open("test.txt") as f:
print f.read()
# output: Hello World!
這是您的問題的答案?
你可以這樣做:當你寫它這樣
import sys
class writer(object):
""" Writes to a file """
def __init__(self, file_name):
self.output_file = file_name
def write(self, something):
with open(self.output_file, "a") as f:
f.write(something)
if __name__ == "__main__":
stdout_to_file = writer("out.txt")
sys.stdout = stdout_to_file
print "noel rocks"
文件只開放。
保留對文件對象的引用,然後在該引用上調用'.close()'。 –
爲什麼'with'不能做你想做的事?你的例子是打開它''r'ead,但是當你用''with'塊完成時它會自動關閉。 – Andy
什麼操作系統?你的問題沒有意義。你的意思是「你怎麼停止寫文件的標準輸出」? – Hamish