Python上传数据

可以使用处理ftp或文件传输协议的python模块将数据上传到服务器。
需要安装模块ftplib才能实现上面功能。

pip install ftplib

1. 使用ftplib

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

import ftplib

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

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

2. 使用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')

当运行上述程序时,可以看到该文件的副本已在服务器中创建。


上一篇:Python Web服务器

下一篇:Python代理服务器

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程