python - 对关闭文件的 I/O 操作;写入文件后尝试在屏幕上打印
问题描述
如果用户选择该选项,我正在尝试将屏幕内容写入文本文件。但是,Python 似乎想要打印"Report Complete."
到我告诉它关闭的 report.txt 文件。我希望“报告完成”在写入文本文件后显示在屏幕上,然后转到散列函数。
import wmi
import sys
import hashlib
c = wmi.WMI()
USB = "Select * From Win32_USBControllerDevice"
print ("USB Controller Devices:")
for item in c.query(USB):
print (item.Dependent.Caption)
print (" ")
print ("======================================")
report = input ("Would you like the results exported to a file? ")
if (report) == "yes":
file = open('report.txt', 'w')
sys.stdout = file
for item in c.query(USB):
print (item.Dependent.Caption)
file.close()
print ("Report complete.")
else:
print ("Job Complete.")
hashInput = input ("Would you like to hash the report? ")
if (hashInput) == "yes":
hash = hashlib.md5(open('report.txt', 'rb').read()).hexdigest()
print ("The MD5 hash value is:", (hash))
else:
print ("Job Complete.")
解决方案
您设置sys.stdout
为一个文件,然后关闭该文件。这使您尝试和打印的所有内容,通常会转到标准输出,然后尝试转到已关闭的文件。如果我可以建议,请不要重新分配sys.stdout
. 没有必要。
if report == "yes":
with open('report.txt', 'w') as fout:
for item in c.query(USB):
print(item.Dependent.Caption, file=fout)
print("Report complete.")
推荐阅读
- python-3.x - 带有 CLI 实用程序的私有仓库中的 Python 包 - 如何部署、使用和构建
- javascript - 输入中的特殊字符以 %nn 形式出现
- javascript - 无法理解 Redux-Saga 中的非阻塞调用
- algorithm - 合并排序算法合并功能不起作用
- vue.js - Axios PUT 对 DRF Api 的请求通过,但未更新
- aws-cdk - 如何在 aws cdk 中使用自定义资源将文件上传到 s3 存储桶
- highcharts - Highcharts 8 - 在窗口调整大小时更改图表类型
- flutter - 如何确定 Flutter Web 应用是在手机还是 PC 上运行?
- algorithm - 如何正确编号两个字母字符?
- javascript - MongooseError [CastError]:模型“residence”的路径“_id”的值“5f37f59e549a291510f1c0dd”转换为 ObjectId 失败