如何在 Python 的请求中使用 FTP

zep*_*ble 5 python ftp python-requests

是否可以使用该requests模块与 FTP 站点交互? requests获取 HTTP 页面非常方便,但是当我尝试使用 FTP 站点时,我似乎收到了 Schema 错误。

有什么我遗漏的东西requests可以让我做 FTP 请求,还是不支持?

Gus*_*pes 3

对于像我一样得到这个答案的人来说,可以使用SO 中另一个问题的答案

它使用urllib.request方法。

简单请求的代码片段如下(在 Python 3 中):

import shutil
import urllib.request as request
from contextlib import closing
from urllib.error import URLError

url = "ftp://ftp.myurl.com"
try:
    with closing(request.urlopen(url)) as r:
        with open('file', 'wb') as f:
            shutil.copyfileobj(r, f)
except URLError as e:
    if e.reason.find('No such file or directory') >= 0:
        raise Exception('FileNotFound')
    else:
        raise Exception(f'Something else happened. "{e.reason}"')
Run Code Online (Sandbox Code Playgroud)