簡體   English   中英

如何根據 Python 中的 if 語句條件將打印命令輸出重定向到文件或屏幕?

[英]How to redirect print command output either to a file or to screen based on an if statement condition in Python?

我有一個打印字符串的簡單代碼。 我想實現一個 if 條件,如果值為 true,它將把字符串打印到文件中,否則它將打印到屏幕上。

如果沒有 2 個相同的打印命令(一個打印到文件,另一個顯示),有什么方法可以做到這一點? 類似於以下代碼段的內容:

filename = 'log.txt'
if SomeCondition == TRUE:
    with open(filename, 'a') as f:
        print("Hello World!", file=f)
else:
    print("Hello World!") #Is there a way to avoid duplicating the print statment?

感謝你的幫助!

用這個:

filename = 'log.txt'
with open(filename, 'a') as f:
    print("Hello World!", file=[None, f][condition])

暫無
暫無

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

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