python requests ftp

Python Requests FTP

Python comes with a built-in module called ftplib for interacting with FTP servers. However, the requests library is a popular alternative for sending HTTP requests in Python, and it can also handle FTP requests.

Installing Requests Library

If you don't have the requests library installed, you can install it using pip:


pip install requests

Connecting to FTP server

To connect to an FTP server using requests, you need to use the requests.Session() method and set the auth parameter to a tuple containing your FTP username and password.

Here's an example:


import requests

session = requests.Session()
session.auth = ('username', 'password')

url = 'ftp://ftp.example.com/'
response = session.cwd(url)

print(response.status_code)

In the above example, we first create a requests.Session() object and set the auth parameter to our FTP username and password. Then, we set the URL of the FTP server and use the session.cwd() method to change the current working directory to that URL. Finally, we print the status code of the response.

Uploading and downloading files

You can use the session.put() method to upload a file to an FTP server and the session.get() method to download a file from an FTP server.

Here's an example:


import requests

session = requests.Session()
session.auth = ('username', 'password')

url = 'ftp://ftp.example.com/folder/file.txt'
file_path = '/path/to/local/file.txt'

with open(file_path, 'rb') as file:
    response = session.put(url, data=file)

print(response.status_code)

response = session.get(url)

with open(file_path, 'wb') as file:
    file.write(response.content)

print(response.status_code)

In the above example, we first create a requests.Session() object and set the auth parameter to our FTP username and password. Then, we set the URL of the file on the FTP server and the path to the local file we want to upload. We use the with statement to open the local file in binary mode and then use the session.put() method to upload the file to the FTP server.

Next, we download the file using the session.get() method and save it to a local file using another with statement in binary mode.

Conclusion

The requests library provides a simple and easy-to-use interface for interacting with FTP servers in Python. Whether you need to upload or download files, or just navigate through directories, the requests library has got you covered.