How to get absolute path on linux when running from another location

Viewed 1432

I want to run a crontab which will run my file every hour at 0 minutes. I have the (sudo) crontab set up with a single command as follows:

0 * * * * /usr/bin/python3 /usr/folder/test.py

The crontab is running and as far as I can tell is correct, but my python file is not returning the absolute path when the file is run from another location.

What I need is a way to guarantee the absolute path of this text file when it is accessed from the root so that my crontab can run the file.

I've tried using both Path(filename).resolve(), and os.path.abspath(filename) but neither of them work.

import os
print(os.path.abspath("checklist.txt"))
python3 usr/folder/test.py

When I run the file "test.py" while within the folder, I get the expected output

python3 test.py

/usr/folder/checklist.txt

however when I run the same file from the root and access it via a path I get a different result, making using crontab impossible in this context

python3 usr/folder/test.py

/checklist.txt

2 Answers

If checklist.txt is in the same folder as your test.py script, then you can use the __file__ variable to get the right path. For example

# The directory that 'test.py' is stored
directory = os.path.dirname(os.path.abspath(__file__))
# The path to the 'checklist.txt'
checklist_path = os.path.join(directory, 'checklist.txt')

__file__ attribute

import os
filename = 'checklist.txt'
abs_path_to_file = os.path.join(os.path.dirname(__file__), filename)

sys module

import os, sys
filename = 'checklist.txt'
abs_path_to_file = os.path.join(os.path.dirname(sys.argv[0]), filename)
Related