How to download a file via FTP with Python ftplib

后端 未结 7 1744
名媛妹妹
名媛妹妹 2020-12-05 12:51

I have the following code which easily connects to the FTP server and opens a zip file. I want to download that file into the local system. How to do that?

#         


        
7条回答
  •  有刺的猬
    2020-12-05 12:59

    Please note if you are downloading from the FTP to your local, you will need to use the following:

    with open( filename, 'wb' ) as file :
            ftp.retrbinary('RETR %s' % filename, file.write)
    

    Otherwise, the script will at your local file storage rather than the FTP.

    I spent a few hours making the mistake myself.

    Script below:

    import ftplib
    
    # Open the FTP connection
    ftp = ftplib.FTP()
    ftp.cwd('/where/files-are/located')
    
    
    filenames = ftp.nlst()
    
    for filename in filenames:
    
        with open( filename, 'wb' ) as file :
            ftp.retrbinary('RETR %s' % filename, file.write)
    
            file.close()
    
    ftp.quit()
    

提交回复
热议问题