繁体   English   中英

python从变量中读取数据并写入文件(无打印),我想稍后将其用作备份数据

[英]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')

with语句的文档

选项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')

有关Pathlib模块的文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM