【发布时间】:2021-02-23 10:08:40
【问题描述】:
我有一个日志文件 mylogfile.log,我想将所有日志从这个文件复制到 python 脚本中的一个变量。我试过了
my_variable = os.system('cat path/to/file/mylogfile.log')
但这不起作用,因为它确实将文本输出到 bash,然后脚本卡住了。 我该怎么做?
【问题讨论】:
我有一个日志文件 mylogfile.log,我想将所有日志从这个文件复制到 python 脚本中的一个变量。我试过了
my_variable = os.system('cat path/to/file/mylogfile.log')
但这不起作用,因为它确实将文本输出到 bash,然后脚本卡住了。 我该怎么做?
【问题讨论】:
with open('path/to/file/mylogfile.log', 'r') as log_file:
# here do the file processing
使用上下文管理器。上面的代码打开文件,然后关闭它。如果在将数据写入文件时发生错误,它会尝试关闭它。上面的代码等价于,除了写入文件:
file = open('file', 'w')
try:
file.write('hey')
finally:
file.close()
【讨论】:
可以直接通过python内置的open函数打开。
my_variable = None
with open('path/to/file/mylogfile.log', 'r') as f:
my_variable = f.read()
# If everything went well, you have the content of the file.
或者,您可以使用子流程:
import subprocess
my_variable = subprocess.check_output('cat path/to/file/mylogfile.log', text=True, shell=True)
【讨论】:
shell=True;见stackoverflow.com/questions/3172470/…
您可以使用file=open(file_path, 'r')在python中读取文件,并使用file.read()获取数据。
【讨论】: