Python - как работать с FTP

Python – how to work with FTP?

Python – how to work with FTP?
– I recently introduced to Google, and was stunned by the number of links with useful (and not so) materials. There are really a lot of them, and so as not to poke around in them, I made a squeeze in the form of the text below, which, I hope, will be useful to you. I – for sure, because most of the entries in my blog are made for myself – a kind of notebook, which sometimes peep.

So FTP.
As it should be for any boring blogger – you definitely need to remember the date the FTP protocol was created (1971).

And also – you need to tell why he – this very FTP – is needed (I’m sure you already know, otherwise why would you look for this material, and even with reference to Python?).

They forced it, and that’s enough. Let’s get down to business.
The easiest way to work with FTP in Python from my point of view is to use the ftplib library, available at link.

You can install it either through pip: pip install, or (if you use, for example, PyCharm ) – through the installation of Plugins: Settings – Plugins.
Connect the library to the code:
import ftplib

ftp = ftplib.FTP(host, ftp_user, ftp_password) – autorization

To make it more clear, we will represent each parameter as a variable:
host = str(input(‘Host?: ‘))
ftp_user = str(input(‘User? :’))
ftp_password = str(input(‘Password? :’))
after which we connect each variable to authorization:
ftp = ftplib.FTP(host, ftp_user, ftp_password)

After that we can:
Receive a welcome message from an FTP server:

    1. text = ftp.getwelcome() # We put in the variable a welcome message from the FTP server
    1. print(text) # We display a message on the screen
  • Go to the necessary directories:

    1. ftp.cwd(‘y’) # go to the directory y
  • Listing file in directory:

    1. list = ftp.nlst() # drive the list of directory contents into the variable list
  • print(list) #display content

    Create directory:

    1. ftp.mkd(‘New’) #Created directory
  • Or deleting all:

    1. ftp.rmd(‘New’) #Deleting directoryг
  • By the way, we can also get a list of all directories:

    1. ftp.dir
  • By the way, we can also delete files:

    1. ftp.delete(‘filename’)
  • And we can get the size of the desired file:

    1. size = ftp.size(‘ResizeImages.exe’) #Request file size ResizeImages.exe
    1. print(size, ‘kb’) #Output file size
  • And you can send the commands you need directly to the FTP server:

    1. FTP.sendcmd() # the command must be specified inside the brackets, yes 🙂
  • Important: the command is written in quotation marks!The commands are:
    ABOR — abort file transfer
    CDUP — up to directory
    CWD — change directory
    DELE — deleting file(DELE filename)
    EPSV — enter advanced passive mode. Applies Instead PASV
    HELP — displays a list of commands accepted by the server.
    LIST — returns a list of directory files. The list is passed through a data connection.
    MDTM — returns file modification time
    MKD — create directory
    NLST — returns a list of directory files in a shorter format than LIST. The list is passed through a data connection.
    NOOP — null operation
    PASS — password
    PASV — enter passive mode. The server will return the address and port to which you need to connect to collect data. The transfer will begin when the following commands are entered:RETR, LIST и т. д.
    PORT — Enter active mode. For example: PORT 12,34,45,56,78,89. Unlike passive mode for data transfer, the server itself connects to the client
    PWD — return the current directory
    QUIT — disconnect
    REIN — reinitialize Connection
    RETR — download file. Before RETR there must be a command PASV or PORT
    RMD — delete directory
    RNFR и RNTO — rename file. RNFR — what rename, RNTO — new file name
    SIZE — return file size
    STOR — file download. Before STOR must be a command PASV or PORT
    SYST — return type operation system (UNIX, WIN, …)
    TYPE — setting file transfer type (бинарный, текстовый)
    USER — user name for ftp-server

    Ok, we’ve figured out the basics … but what if, for example, you want to rename a file? Everything is simple:

  • ftp.rename(‘Old_name’, ‘New_name’)
  • Oh, I completely forgot … but how to save files to FTP and merge from there? The following will help you to upload to FTP:
  • storlines – used to download text files: txt, html, rst ets…
    1. ftp.storlines(‘filename’)
  • storbinary – necessary to download binary files:pdf, xls и ets..
      ftp.storbinary(‘filenames’)
  • And to save the C FTP file, we use the construction:
      1. with open(‘path to directory for saving file’, ‘wb’) as f:
      1. ftp.retrbinary(‘RETR ‘ + ‘filename’, f.write)
    • It seems like everyone. In case of questions – please write 🙂
      Thanks!!
    • UPD: thanks to one of the readers of the blog 🙂 I noted that it would be nice to add information about the timeout for waiting for a connection to the server. Add 🙂

      1. ftp = ftplib.FTP('127.0.0.1', timeout=100)

      As you can see – everything is simple 😉