Python 上传数据


我们可以使用处理 ftp 或文件传输协议的 python 模块将数据上传到服务器。

我们需要安装模块 ftplib 实现这一目标。

pip install ftplib

使用 ftplib


在下面的示例中,我们使用 FTP 方法连接到服务器,然后提供用户凭据。接下来我们提到文件的名称和在服务器中发送和存储文件的 storbinary 方法。

import ftplib

ftp = ftplib.FTP("127.0.0.1")
ftp.login("username", "password")
file = open('index.html','rb')   
ftp.storbinary("STOR " + file, open(file, "rb"))
file.close()                                   
ftp.quit() 

当我们运行上述程序时,我们观察到该文件的副本已在服务器中创建。

使用 ftpreety


与 ftplib 类似,我们可以使用 ftpreety 安全地连接到远程服务器并上传文件。我们也可以使用 ftpreety 下载文件。下面的程序说明相同。

from ftpretty import ftpretty

# Mention the host
host = "127.0.0.1"

# Supply the credentisals
f = ftpretty(host, user, pass )

# Get a file, save it locally
f.get('someremote/file/on/server.txt', '/tmp/localcopy/server.txt')

# Put a local file to a remote location
# non-existent subdirectories will be created automatically
f.put('/tmp/localcopy/data.txt', 'someremote/file/on/server.txt')

当我们运行上述程序时,我们观察到该文件的副本已在服务器中创建。