Friday, February 4, 2022

[SOLVED] Writing to data in Python to a local file and uploading to FTP at the same time does not work

Issue

I have this weird issue with my code on Raspberry Pi 4.

from gpiozero import CPUTemperature
from datetime import datetime
import ftplib

cpu = CPUTemperature()
now = datetime.now()
time = now.strftime('%H:%M:%S')

# Save data to file
f = open('/home/pi/temp/temp.txt', 'a+')
f.write(str(time) + ' - Temperature is: ' + str(cpu.temperature) + ' C\n')

# Login and store file to FTP server
ftp = ftplib.FTP('10.0.0.2', 'username', 'pass')
ftp.cwd('AiDisk_a1/usb/temperature_logs')
ftp.storbinary('STOR temp.txt', f)

# Close file and connection
ftp.close()
f.close()

When I have this code, script doesn't write anything to the .txt file and file that is transferred to FTP server has size of 0 bytes.

When I remove this part of code, script is writing to the file just fine.

# Login and store file to FTP server
ftp = ftplib.FTP('10.0.0.2', 'username', 'pass')
ftp.cwd('AiDisk_a1/usb/temperature_logs')
ftp.storbinary('STOR temp.txt', f)

...

ftp.close()

I also tried to write some random text to the file and run the script, and the file transferred normally.

Do you have any idea, what am I missing?


Solution

After you write the file, the file pointer is at the end. So if you pass file handle to FTP, it reads nothing. Hence nothing is uploaded.

I do not have a direct explanation for the fact the local file ends up empty. But the strange way of combining "append" mode and reading may be the reason. I do not even see a+ mode defined in open function documentation.


If you want to both append data to a local file and FTP, I suggest your either:

  • Append the data to the file – Seek back to the original position – And upload the appended file contents.
  • Write the data to memory and then separately 1) dump the in-memory data to a file and 2) upload it.


Answered By - Martin Prikryl
Answer Checked By - Senaida (WPSolving Volunteer)