在 Python ftplib 中创建并上传到 FTP 的文件为空

File created and uploaded to FTP in Python ftplib is empty

我正在尝试使用 json 与 Python 进行简单的服务器-客户端交互。但是现在我遇到了一个问题,我的 .json 文件确实上传了,但是在服务器端它是空的。

你能帮帮我吗?

import json
import urllib.request
import os
import time
import ftplib
import fileinput
from ftplib import FTP

url = urllib.request.urlopen("http://example.com/path/data.json").read()
rawjson = url.decode("utf-8")

number = input("Bank number: ")

result = json.loads(url)

name = result[number]["name"]
salary = result[number]["salary"]

strsalary = str(salary)

newsalary = input("New salary: ")

os.system("wget http://example.com/path/data.json")

newtext = rawjson.replace(strsalary, newsalary)

textfile = open("data.json", "w")
textfile.write(newtext)

#domain name or server ip:
ftp = FTP('example.com','usr','pswd')
ftp.cwd("/path")
file=open('data.json', 'rb')
ftp.storbinary('STOR data.json', file)

这是客户端脚本,我想通过 json 使用简单的网络服务器而不是 Python 服务器创建客户端服务器交互。

您写入文本文件的代码没有关闭它。因此,在您尝试读取文件以进行上传时,文件可能尚未完全刷新到磁盘。

要正确关闭文件,最佳做法是使用 with 块:

with open("data.json", "w") as textfile:
    textfile.write(newtext)

尽管如果您只是将文件用作临时存储要上传到 FTP 的 data/text 的一种方式,则根本不必使用物理文件。

改用内存中类似文件的对象,例如 StringIO(或 BytesIO):

from io import StringIO
ftp.storbinary('STOR data.json', StringIO(newtext))

另见 Can I upload an object in memory to FTP using Python?


下载文件使用与上传文件完全不同的 API 也很奇怪。你应该使用 FTP.retrbinary。同样与上传类似,您根本不需要将内容存储到本地文件。您可以将内容下载到内存中。但这超出了这个问题的范围。