我想把python运行完程序后最终的控制台输出 输出到一个txt 或word 或json 文件中。怎么操作?
定义一个自己的print,哪儿需要哪儿调用
定义:
log = open('log.txt', 'a+', encoding='utf-8')
def print_(str_):
print(f"{str_}")
log.write(f"{str_}\r\n")
调用:
import time
from t2 import print_
print_(time.time())
以下代码供您参考
控制台输出输出到txt文件
f = open('log.txt','w')
for i in range(10):
#打印输出到控制台
print(str(i))
#输出到文件print函数
print(str(i), file=f)
f.close()
控制台输出内容写入到word
import docx
from docx import shared
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
doc=docx.Document() #创建内存中的word文档对象
str1 = "控制台输出内容1"
print(str1)
doc.add_paragraph(str1) #写入若干段落
str2 = "控制台输出内容2"
print(str2)
doc.add_paragraph(str2) #写入若干段落
doc.save("test.docx") #保存才能看到结果
控制台输出写入到json
import json
with open("test.json","w") as f:
test_dict = {'one':1, 'two':2}
json_str = json.dumps(test_dict)
print(json_str)
#解析JSON数据,返回python中的的字典数据类型
new_dict = json.loads(json_str)
#将python dict数据写入json文件中
json.dump(new_dict,f)
print("加载入文件完成...")
可以用一个列表存放你的控制台所有输出,最后通过python的操作文件方式,往文件中写入就行了
content_list=['这是第一个输出','这是第二个输出']
content_str=”””.join(content_list)
f = open("xxx.txt","w")
f.write(content_str)
f.close()
1.重定向标准输出。
import sys
sys.stdout = open("xxx.txt", "w")
print("hello")
print("world")
print("...")
sys.stdout.close() #关闭文件
这样,所有的输出内容就被输出到了xxx.txt。
2.上面的方法比较简单,但是输出内容只能输出到文件,不会显示到控制台上。可以用以下代码实现输出到两个地方。
class Stdout:
def __init__(self, stdout):
self.file = open("xxx.txt", "w")
self.stdout = stdout
def write(self, message):
self.stdout.write(message)
self.file.write(message)
sys.stdout = Stdout(sys.stdout)
print("hello")
print("world")
print("...")
sys.stdout.file.close()
通过这种方式,输出不仅输出到控制台,而且输出到xxx.txt。
3.还可以指定print函数的file参数。
file = open("xxx.txt", "w")
print("Hello", file=file)
file.close()
但是比较麻烦
把结果赋值给变量 content
f = open("text.txt",'wb')
f.write(content)
f.close()
或者将结果输出,在运行时 python test.py >./test.txt 重定向输出结果。
我只说linux啊,保存控制台的输出不适合写在python代码中,会干扰主代码,交给专业的linux,同时输出到控制台和文件,还能方便指定输出的文件名
# 1. python输出重定向
with open('redirect.txt', 'w') as f:
sys.stdout = f
print("Hello World")
# 2. linux命令重定向
python run.py > result.txt
将你要打印的内容写入一个文件中即可,下面例子是将test.py在中打印的内容写入到hello.txt中
你的具体场景是什么,是保存操作日志还是排查问题,如果排查问题可以通过控制台输出日志文件比较好
建议通过控制台方式
python<name.py>name.log
import sys
# 日志打印
class Logger(object):
def __init__(self, filename='default.log', stream=sys.stdout):
self.terminal = stream
self.log = open(filename, 'w')
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
# 保存日志 传入要保存的文件名
sys.stdout = Logger(r'a.txt')
# 代码主干部分
print("hello")
print(123)
print("world")
# 写入完成后,要及时关闭。
sys.stdout.log.close()
可以使用重定向
python app.py > output.txt
简单的话就是重定向,只不过把你的程序所有的输出都导出到输出文件中了,如果需要筛选部分输出的话,就是简单的文件操作 open("你的文件名",'wb'),然后f.write(“你的内容”),最后f.close(),至于其他格式,可以在导出txt文件后另存为或格式转换就ok了
重定向:
打开命令行或者终端:输入 python 你的python程序 > out.txt
输出就会保存到out.txt文件中
重定向 python aaa.py > aaaa.txt
不知道你这个问题是否已经解决, 如果还没有解决的话:他居然有这么多方法,直接将输出内容写到文件