Python:从FTP服务器下载文件

新手上路,请多包涵

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

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

我在 请求库网站 上找不到任何文档。

原文由 user1507455 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 649
2 个回答

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)

蟒蛇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)

原文由 jfs 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以试试这个

import ftplib

path = 'pub/Health_Statistics/NCHS/nhanes/2001-2002/'
filename = 'L28POC_B.xpt'

ftp = ftplib.FTP("Server IP")
ftp.login("UserName", "Password")
ftp.cwd(path)
ftp.retrbinary("RETR " + filename, open(filename, 'wb').write)
ftp.quit()

原文由 Rakesh 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题