python将控制台输出保存到文件 您所在的位置:网站首页 python如何将print输出值一个个的保存到表格文件中 python将控制台输出保存到文件

python将控制台输出保存到文件

2023-11-03 22:17| 来源: 网络整理| 查看: 265

在平时工作中,有时我们需要将控制台输出保存到文件

1.命令行用>覆盖写入和>>追加写入

for i in range(10000): print(i) View Code #将控制台输出覆盖写入到文件

python myprint.py > myprint.txt

#将控制台输出追加写入到文件

python myprint.py >> myprint.txt

2.将sys.stdout输出到文件

import sys import time f=open("myprint.txt","w+") sys.stdout=f for i in range(1000): print(i*9) View Code

缺点:只能保存到文件,但控制台无输出

3.利用print函数中的file参数

import sys import time f=open("myprint.txt","w+") for i in range(100): print("--{}--".format(i**2),file=f,flush=True) print("--{}--".format(i ** 2),file=sys.stdout) time.sleep(0.5) View Code

将控制台输出的同时即时保存到文件

print函数中的file参数,file=f,输出到文件;file=sys.stdout,输出到终端;flush=True,即时刷新

4.用类实现

import sys class Logger(object): def __init__(self, filename='default.log', stream=sys.stdout): self.terminal = stream self.log = open(filename, 'a') def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): pass sys.stdout = Logger(stream=sys.stdout) # now it works print('print something') print("output") View Code

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有