[英]python read data from variable and write to a file (no print) which i wanted to use later as backup data
我是python和編程新手。 開始為我的項目嘗試一些事情。
我的問題如下
p=subprocess.Popen(Some command which gives me output],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
p.wait()
content=p.stdout.readlines()
for line in content:
filedata=line.lstrip().rstrip()
-----> 我希望此文件數據輸出打開並保存到文件中。
如果我使用打印文件數據,它可以正常工作,並提供我想要的確切信息,但我不想打印,以后想使用此數據。
提前致謝..
您可以通過以下兩種方式來實現。
選項一使用了更傳統的文件處理方式,我使用過with語句,使用with語句您不必擔心關閉文件
選項二,它使用pathlib模塊,這是3.4版中的新功能(我建議使用此功能)
somefile.txt是文件系統中的完整文件路徑。 我還提供了文檔鏈接,強烈建議您仔細閱讀這些鏈接。
選項一
p=subprocess.Popen(Some command which gives me output],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
p.wait()
content=p.stdout.readlines()
for line in content:
filedata=line.lstrip().rstrip()
with open('somefile.txt', 'a') as file:
file.write(filedata + '\n')
選項2-適用於Python 3.4或更高版本
import pathlib
p=subprocess.Popen(Some command which gives me output],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
p.wait()
content=p.stdout.readlines()
for line in content:
filedata=line.lstrip().rstrip()
pathlib.Path('somefile.txt').write_text(filedata + '\n')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.