0

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?

Romeo Ninov
  • 6,538
  • 1
  • 22
  • 31
  • https://stackoverflow.com/a/1270970/1390548 see if this helps – Jawad Dec 09 '19 at 22:51
  • Somehow the current directory must be /root/ when this cron job is executed. Try to find out why, and fix it. As an alternate, even "* * * * * cd /root/project/; python3 test.py" should work – Shoonya Dec 09 '19 at 23:00
  • thank you ! I am so happy that so many people helped me. – lch-howger Dec 10 '19 at 12:42

1 Answers1

0

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')
Romeo Ninov
  • 6,538
  • 1
  • 22
  • 31