将 Python 中的数据写入本地文件并同时上传到 FTP 不起作用

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

我在 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()

当我有这段代码时,脚本不会向 .txt 文件写入任何内容,并且传输到 FTP 服务器的文件的大小为 0 字节。

当我删除这部分代码时,脚本可以正常写入文件。

# 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()

我也试过向文件和运行脚本写入一些随机文本,文件传输正常。

你知道吗,我错过了什么?

写入文件后,文件指针指向末尾。因此,如果您将文件句柄传递给 FTP,它什么也读不到。因此没有上传任何内容。

对于本地文件最终为空这一事实,我没有直接的解释。但是将"append"模式和阅读结合起来的奇怪方式可能就是这个原因。我什至没有看到 open function documentation 中定义的 a+ 模式。


如果您既想将数据附加到本地文件又想 FTP,我建议您:

  • 将数据追加到文件中 – 寻回原位置 – 并上传追加的文件内容。
  • 将数据写入内存,然后分别1)将内存中的数据转储到文件中,2)上传。