-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?

0

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

You should probably avoid shell=True; see stackoverflow.com/questions/3172470/…
0

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

Comments

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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.