Search code examples
pythoncron

Using crontab but python3 running path is root diretory


Here is my python code: /root/project/test.py

file = open('./test.txt', 'a')
file.write('Hello World\n')
file.close()

when I use crontab

* * * * * python3 /root/project/test.py

to run the python demo

I want the test.txt to be created and writed in the /root/project/ but actually it is created and writed in the /root/

I am so sad. How can I do it without change the python code?


Solution

  • When you run cron record for particular user it use home directory of this user. You can try two different approaches:

    1. do cd in the cron record: * * * * * cd /root/project; python3 test.py
    2. set path (absolute or relative in your code): file = open('project/test.txt', 'a') or file = open('/root/project/test.txt', 'a')