Python:从 FTP 服务器下载文件

标签 python download ftp python-requests

我正在尝试下载一些公共(public)数据文件。我截屏以获取文件的链接,它们看起来都像这样:

ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/nhanes/2001-2002/L28POC_B.xpt

我在 Requests library website 上找不到任何文档.

最佳答案

requests 库不支持 ftp:// 链接。

要从 FTP 服务器下载文件,您可以使用 urlretrieve :

import urllib.request

urllib.request.urlretrieve('ftp://server/path/to/file', 'file')
# if you need to pass credentials:
#   urllib.request.urlretrieve('ftp://username:password@server/path/to/file', 'file')

urlopen :

import shutil
import urllib.request
from contextlib import closing

with closing(urllib.request.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

Python 2:

import shutil
import urllib2
from contextlib import closing

with closing(urllib2.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

关于Python:从 FTP 服务器下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11768214/

相关文章:

regex - 如何通过 ftp 连接获取字母数字大于 Linux 命令行 (bash) 中指定的文本的文件列表?

java - 自动将 Maven 编译的 jar 上传到 FTP 位置?

git - 使用 git-ftp 将子文件夹推送到 ftp

python - 如何将八进制字符串更改为char?

python - 在 python 中使用 tkinter 为我的简单聊天机器人创建一个简单的 gui 时遇到问题

java - 如何在网络服务器中添加用户定义的扩展效果

asp.net - 从 ASP .Net 下载文件时,文本文件会附加 HTML 内容

python - pandas to_timedelta 忽略单位参数?

python - JSONDecodeError Django

ruby-on-rails - Rails 'link_to' 立即下载图像而不是在浏览器中打开它