我正在尝试下载一些公共(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/