python ftp upload

To upload a file to an FTP server using Python, you can use the built-in ftplib library. Below is an example of how to upload a file to an FTP server.

Code Example for FTP Upload

from ftplib import FTP

def upload_file(ftp_host, ftp_user, ftp_password, file_path, remote_path):
    try:
        # Connect to the FTP server
        ftp = FTP(ftp_host)
        ftp.login(user=ftp_user, passwd=ftp_password)
        print(f"Connected to {ftp_host}")

        # Open the file in binary mode
        with open(file_path, 'rb') as f:
            # Upload the file to the specified path on the FTP server
            ftp.storbinary(f'STOR {remote_path}', f)
            print(f"Successfully uploaded {file_path} to {remote_path}")

        # Close the connection
        ftp.quit()
    except Exception as e:
        print(f"Error: {e}")

# Example usage
ftp_host = 'ftp.example.com'
ftp_user = 'your_username'
ftp_password = 'your_password'
file_path = 'local_file.txt'  # Path to the local file you want to upload
remote_path = 'remote_directory/remote_file.txt'  # Path on the server

upload_file(ftp_host, ftp_user, ftp_password, file_path, remote_path)

Explanation

  1. Importing the library:
    We import the FTP class from ftplib to handle the FTP connection.

  2. Connecting to the FTP server:
    We use ftp.login() to log in using the provided credentials.

  3. Uploading the file:

    • We open the file in binary mode ('rb').
    • We use the ftp.storbinary() method to upload the file. The first parameter is the FTP command ('STOR'), followed by the remote path where the file will be uploaded.
    • The second parameter is the file object to upload.
  4. Handling exceptions:
    We wrap the code in a try...except block to catch any connection or file transfer errors.

  5. Closing the connection:
    After the transfer is complete, the FTP connection is closed using ftp.quit().

Notes:

  • Make sure the paths are correct: Ensure both file_path and remote_path are valid.
  • Firewall and permissions: Ensure the FTP server allows uploads and that you have the necessary permissions.
  • FTP in passive mode: If you encounter connection issues, you can switch to passive mode using ftp.set_pasv(True). This might be necessary if the server is behind a firewall.

This code will help you upload files via FTP easily using Python. If your server supports SFTP (secure FTP), you'll need to use a different library, such as paramiko. Let me know if you need help with that!

댓글

이 블로그의 인기 게시물

JAXB @XmlTransient 예제

Screenshot of a web page using Puppeteer with a specific browser width, 웹페이지 스크린샷

how to make inactive kafka topic, 카프카 토픽 비활성화

ssh-copy-id in ansible

What are 5 creative things I could do with my kids' art, 아이와 함께하는 창의적 놀이

How to catch exceptions on Future in Java, 자바 Future 에러 잡기

To change the ESE index in Fluent Bit

Consume a topic from kafka by Python

패션 하의, Pants, Skirts, Shorts, Skorts

ftplib.error_perm: 550 Permission denied