首页 > 解决方案 > 将Python中的数据写入本地文件并同时上传到FTP不起作用

问题描述

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

我还尝试将一些随机文本写入文件并运行脚本,文件传输正常。

你有什么想法,我错过了什么?

标签: pythonfileraspberry-piftpftplib

解决方案


写入文件后,文件指针位于末尾。因此,如果您将文件句柄传递给FTP,它不会读取任何内容。因此没有上传任何内容。

对于本地文件最终为空的事实,我没有直接的解释。但是“追加”模式和阅读结合的奇怪方式可能是原因。我什至没有看到函数文档a+中定义的模式。open


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

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

推荐阅读