首页 > 解决方案 > 对关闭文件的 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.")

标签: python

解决方案


您设置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.")

推荐阅读