【问题标题】:Copy text file from linux to python variable [duplicate]将文本文件从linux复制到python变量[重复]
【发布时间】:2021-02-23 10:08:40
【问题描述】:

我有一个日志文件 mylogfile.log,我想将所有日志从这个文件复制到 python 脚本中的一个变量。我试过了

my_variable = os.system('cat path/to/file/mylogfile.log')

但这不起作用,因为它确实将文本输出到 bash,然后脚本卡住了。 我该怎么做?

【问题讨论】:

    标签: python linux bash


    【解决方案1】:
    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()
    

    【讨论】:

      【解决方案2】:

      可以直接通过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)
      

      【讨论】:

      【解决方案3】:

      您可以使用file=open(file_path, 'r')在python中读取文件,并使用file.read()获取数据。

      【讨论】:

        猜你喜欢
        • 2018-10-13
        • 2017-02-19
        • 2020-08-11
        • 1970-01-01
        • 1970-01-01
        • 2018-05-24
        • 2013-11-13
        • 2021-05-16
        • 2016-10-14
        相关资源
        最近更新 更多