Forums

Optimal way to avoid FileNotFoundError when going from local/Console to scheduled tasks

This is (admittedly) probably a noob question, but I'm wondering what the optimal way is to avoid this.

When running a script locally or from the console, code like this:

df = pd.read_csv('some_data.csv')

..works perfectly fine. However, attempt to run this same code as a scheduled Task with a Command, like so:

python3 /home/tjw0000/subfolder/subfolder/subfolder/script.py

breaks the script and will return:

FileNotFoundError: File b'last_trade.csv' does not exist

Any advice on the best way to write my code locally/Console so it won't break when I run it as a task? Do I have to go through and make all file-linking explicit with the exact ? The problem with that, is I have to then maintain two separate codebases, one for running the code locally/Console, and one for running the code as a scheduled task. Not exactly fun :(


EDIT: I may have found my own answer: https://help.pythonanywhere.com/pages/NoSuchFileOrDirectory/

use Python's magic file method in your code:

import os  
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))  
my_file = os.path.join(THIS_FOLDER, 'myfile.txt')

Yup, that's the best way to do it. The reason it's not working when you do it from a scheduled task is that the scheduled task is running with your home directory as its working directory.

For completeness, an alternative would have been to change the working directory for the scheduled task; it would look something like this:

cd /home/tjw0000/subfolder/subfolder/subfolder/; python3 script.py