程序比较大,运行时间又长的时候,不想等着结果,只要先确保程序功能正确无误,可以把需要的结果print然后保存到TXT文件中,超级方便
# 创建一个txt文件,文件名为mytxtfile
def text_create(name):
desktop_path = "C:\\Users\\Administrator\\PycharmProjects\\EmotionRecog\\venv\\Scripts\\src\\mylog\\"
# 新创建的txt文件的存放路径
full_path = desktop_path + name + '.txt' # 也可以创建一个.doc的word文档
file = open(full_path, 'w')
filename = 'log'
text_create(filename)
output = sys.stdout
outputfile = open("C:\\Users\\Administrator\\PycharmProjects\\EmotionRecog\\venv\\Scripts\\src\\mylog\\" + filename + '.txt', 'w')
sys.stdout = outputfile
balabalabalabalabala # 运算部分
print('accuracy = ', accuracy*100, file=outputfile)
outputfile.close() # close后才能看到写入的数据
重点是print里面要说明file=outputfile,并且程序末尾要关闭文件,不然都不