Clo*_*one 47 python python-3.x
有没有办法将所有打印输出保存到python中的txt文件?让我说我的代码中有这两行,我想将打印输出保存到一个名为的文件output.txt
.
print ("Hello stackoverflow!")
print ("I have a question.")
Run Code Online (Sandbox Code Playgroud)
我希望output.txt
文件包含
Hello stackoverflow!
I have a question.
Run Code Online (Sandbox Code Playgroud)
Aar*_*sen 84
给出print
一个file
关键字参数,其中参数的值是文件流.我们可以使用以下open
函数创建文件流:
print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))
Run Code Online (Sandbox Code Playgroud)
所述
file
参数必须是与对象write(string)
方法; 如果它不存在或None
,sys.stdout
将被使用.
以及以下文档open
:
打开
file
并返回相应的文件对象.如果无法打开文件,OSError
则引发a.
在"a"
作为第二个参数open
是指"追加" -换句话说,文件的现有内容不会被覆盖.如果您希望覆盖该文件,请使用"w"
.
Rom*_*ein 13
您可以将stdout重定向到文件"output.txt":
import sys
sys.stdout = open('output.txt','wt')
print ("Hello stackoverflow!")
print ("I have a question.")
Run Code Online (Sandbox Code Playgroud)
使用日志记录模块
def init_logging():
rootLogger = logging.getLogger('my_logger')
LOG_DIR = os.getcwd() + '/' + 'logs'
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
rootLogger.addHandler(fileHandler)
rootLogger.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler()
rootLogger.addHandler(consoleHandler)
return rootLogger
Run Code Online (Sandbox Code Playgroud)
获取记录器:
logger = init_logging()
Run Code Online (Sandbox Code Playgroud)
并开始记录/输出:
logger.debug('Hi! :)')
Run Code Online (Sandbox Code Playgroud)
小智 5
另一种变体可以是...之后一定要关闭文件
import sys
file = open('output.txt', 'a')
sys.stdout = file
print("Hello stackoverflow!")
print("I have a question.")
file.close()
Run Code Online (Sandbox Code Playgroud)
另一种无需更新 Python 代码的方法是通过 console 重定向。
基本上,print()
像往常一样使用Python 脚本,然后从命令行调用脚本并使用命令行重定向。像这样:
$ python ./myscript.py > output.txt
Run Code Online (Sandbox Code Playgroud)
您的output.txt
文件现在将包含 Python 脚本的所有输出。
编辑:
解决评论;对于 Windows,将正斜杠更改为反斜杠。
(即.\myscript.py
)