Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 423
zephyrthenoble Avatar asked Jun 03 '14 19:06

zephyrthenoble


People also ask

How do I transfer files using FTP in Python?

FTP(File Transfer Protocol) To transfer a file, 2 TCP connections are used by FTP in parallel: control connection and data connection. For uploading and downloading the file, we will use ftplib Module in Python. It is an in-built module in Python.

What is FTPR in Python?

File Transfer Protocol (FTP) is a standard network protocol for the transfer of files to and from the server. Python has a module called ftplib that allows the transfer of files through the FTP protocol.


1 Answers

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}"')
like image 183
Gustavo Lopes Avatar answered Oct 24 '22 23:10

Gustavo Lopes