最新方法,用with open()
import os
t = 5
s = 'hello world!'
with open('test.txt','a') as file0:
print('%d' % t,'%s' % s,file=file0)
第一种方法:在代码import之后,其余所有代码之前执行,这个代码块之前的print都不会输出的
import sys
import os
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
self.log = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
path = os.path.abspath(os.path.dirname(__file__))
type = sys.getfilesystemencoding()
sys.stdout = Logger('a.txt')
print(path)
print(os.path.dirname(__file__))
print('------------------')
for i in range(5, 10):
print("this is the %d times" % i)
第二种方法:在终端执行
python<你的python文件.py>outputfile.txt
参考链接:
1.https://blog.youkuaiyun.com/young2415/article/details/76595318
2.https://blog.youkuaiyun.com/w76190504/article/details/81085055
本文介绍了两种在Python中将标准输出重定向到文件的方法。第一种是在代码中使用with open()结合print()函数直接写入文件。第二种是通过创建Logger类,重定向sys.stdout到指定的日志文件。此外,还提供了在终端执行Python脚本并直接输出到文件的方法。
1169





