[英]How to print to screen and save to file in one-line?
是否可以一行打印到屏幕並保存到文件?
以下保存到文件:
with open('file.txt', 'a') as f:
print('hello world', file=f)
目前要打印到屏幕並保存到文件必須執行以下操作:
print['hello world')
print('hello world', file=f)
我找不到單行的任何答案。
我想可以定義一個 function 來避免代碼中的行,但仍然想知道是否可以在一行中完成所有操作
您正在尋找適合 Python 的T 恤。這樣的 package - T 恤 - 存在於 PyPI 中。
你也可以用幾行代碼自己構建一個——我維護的一個大 package 的原作者就是這樣做的,我的代碼至今仍在使用它。 當然,不需要那個,因為 package 可用。
嘗試下面的代碼片段,我在 Jupyter Notebook 中成功使用了它
f=open('file.txt','a');print('hello world');f.write('hello world');f.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.