Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 3755

Troubleshooting • Re: Solution - using Cron to write to a CSV file

$
0
0
Well this unusual. I have a python program that writes its results to a CSV file, but which wouldn't do so when run via a Cron job. I was minutes away from giving up and asking for help when I accidentally solved the problem.

As I've not found this solution online despite extensive searching, I'm posting it here in the hope that it may be useful to someone else.

The python file ends with the following code:

Code:

f = open("/home/pi/sensorData.csv", "a", encoding="ISO-8859-1")f.write(f"{', '.join(data.values())}\n")f.close()
and this was my last-but-one attempt in Crontab, which didn't work:

Code:

0,15,30,45 * * * * /usr/bin/python3 /home/pi/sensor.py >> /home/pi/sensorData.csv

The solution was just to change the file extension in the Cron job:

Code:

0,15,30,45 * * * * /usr/bin/python3 /home/pi/sensor.py >> /home/pi/sensorData.txt
...which successfully writes to sensorData.csv, and not sensorData.txt

Of course a CSV file is a effectively text file, but that was an unexpected result.
The reason this happened is because originally you were trying to redirect the output of the Python script to the same file that you were creating in the script itself. Since the Python script doesn't produce any screen output there's nothing to redirect, so the resulting file is empty. Your solution, to redirect to a differently named file, works because you are no longer trying to overwrite the file you created.

The >> operator should append to the file, but I expect it's appending to a file that initially doesn't exist.

Statistics: Posted by ame — Sat Nov 02, 2024 10:48 pm



Viewing all articles
Browse latest Browse all 3755

Trending Articles