Python:通过FTP下载文件
我正在尝试下载一些公共数据文件。 我抓取屏幕快照以获取文件的链接,这些链接看起来都像这样:
ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/nhanes/2001-2002/L28POC_B.xpt
我在请求库网站上找不到任何文档。1
8个解决方案
60 votes
requests库不支持ftp链接。
要从FTP服务器下载文件,您可以:
import urllib
urllib.urlretrieve('ftp://server/path/to/file', 'file')
# if you need to pass credentials:
# urllib.urlretrieve('ftp://username:password@server/path/to/file', 'file')
要么:
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)
Python3:
import shutil
import urllib.request as request
from contextlib import closi