簡體   English   中英

如何增加在python中寫入文件的行數

[英]How to increase the amount of lines written to a file in python

因此,我有一個程序,可以將程序的輸出寫入文本文件,但不會將要打印出的所有行寫到文本文件中。 有什么辦法可以增加這個? 這是一個代碼示例:

import sys
sys.stdout = open('thefile.txt', 'w')
#Lots of printing here, but not all is written to the text file.

有沒有辦法增加這個限制? 或者沒有? 編輯:沒關系,我只是發現了問題,我無意中結束了程序。

您很可能會錯過為sys.stderr做同樣的事情。 但是,您不應該那樣做。 如果您想將stdout和stderr轉到文件,則只需調用程序即可

python prog.py >thefile.txt 2>&1

您很有可能會看到將輸出到sys.stderrsys.stdout 為了進行測試,可以在兩個地方使用相同的文件句柄:

fh = open('thefile.txt', 'w')
stdout_, stderr_ = sys.stdout, sys.stderr
sys.stdout = sys.stderr = fh
# the code you're importing or printing from
# to restore the defaults.
sys.stdout = stdout_
sys.stderr = stderr_

除了重定向標准錯誤輸出外,別忘了在寫入文件后正確關閉文件。 如果您不這樣做,則輸出可能無法正確同步,並且文件末尾可能會丟失。 Python的with結構非常適合以下情況:

with open('thefile.txt', 'w') as f:
    # do the magic here
    pass

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM