-1

I have a log file mylogfile.log and I want to copy all the logs from this file to a variable in python script. I tried to

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

but that won't work because it really output the text to the bash and then the script stuck. How can I do that?

dddd4
  • 21
  • 1
  • 3

3 Answers3

2

You can directly open it via the python built-in open function.

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.

Alternatively, you can use subprocess:

import subprocess

my_variable = subprocess.check_output('cat path/to/file/mylogfile.log', text=True, shell=True)
ErdoganOnal
  • 800
  • 6
  • 13
  • You should probably avoid `shell=True`; see https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess – tripleee Nov 11 '20 at 12:45
0

You can read files in python using file=open(file_path, 'r') and get the data using file.read().

Tamir
  • 1,224
  • 1
  • 5
  • 18
0
with open('path/to/file/mylogfile.log', 'r') as log_file:
    # here do the file processing

Use context managers. The above code opens the file and then closes it. If an error occurs while writing the data to the file, it tries to close it. The above code is equivalent to, except it writes into the file:

file = open('file', 'w')
try:
    file.write('hey')
finally:
    file.close()
Marko M
  • 36
  • 1
  • 6