zephyrthenoble
zephyrthenoble

Reputation: 1487

How to use FTP with Python's requests

Is it possible to use the requests module to interact with a FTP site? requests is very convenient for getting HTTP pages, but I seem to get a Schema error when I attempt to use FTP sites.

Is there something that I am missing in requests that allows me to do FTP requests, or is it not supported?

Upvotes: 6

Views: 6086

Answers (1)

Gustavo Lopes
Gustavo Lopes

Reputation: 4174

For anyone who comes to this answer, as I did, can use this answer of another question in SO.

It uses the urllib.request method.

The snippet for a simple request is the following (in 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}"')

Upvotes: 3

Related Questions