📜  Python -FTP(1)

📅  最后修改于: 2023-12-03 15:18:53.106000             🧑  作者: Mango

Python - FTP

FTP stands for File Transfer Protocol which is used to transfer files between two computers. In Python, we have a built-in package called ftplib which can be used to make FTP connections and transfer files.

Establishing an FTP Connection

To establish an FTP connection, we need to create an object of class FTP from the ftplib package. We will provide the hostname, username, and password of the FTP server we want to connect to as arguments to the constructor of the FTP class.

from ftplib import FTP

ftp = FTP('ftp.example.com', 'username', 'password')
Listing Files and Directories

To list the files and directories present on the FTP server, we can use the nlst() method which returns a list of filenames.

file_list = ftp.nlst()
print(file_list)
Downloading Files

To download a file from the FTP server to our local machine, we can use the retrbinary() method of the FTP class. We will provide the filename and a callback function to this method.

def download_file(filename):
    with open(filename, 'wb') as file:
        ftp.retrbinary('RETR ' + filename, file.write)

download_file('example.txt')
Uploading Files

To upload a file from our local machine to the FTP server, we can use the storbinary() method of the FTP class. We will provide the filename and a file object to this method.

def upload_file(filename):
    with open(filename, 'rb') as file:
        ftp.storbinary('STOR ' + filename, file)

upload_file('example.txt')
Closing the Connection

Once we are done with our FTP operations, we should close the connection to the FTP server.

ftp.quit()
Conclusion

Python provides a powerful library for working with FTP connections, making file transfers a breeze. With the ftplib package, we can easily establish an FTP connection, list files and directories, download and upload files, and close the connection once we're done.