Search code examples
pythonzipftplib

FTP upload using python, having trouble with rb mode


I have a zip file to upload. I know how to upload it.I open the file with "Rb" mode. When i want to extract the zip file that i uploaded i get an error and files in the ZIP archive are gone, i think that's because of the "Rb" mode . I don't know how to extract my uploaded file.

Here is the code:

filename="test.zip"
ftp=ftplib.FTP("ftp.test.com")
ftp.login('xxxx','xxxxx')
ftp.cwd("public_html/xxx")
myfile=open("filepath","rb")
ftp.storlines('STOR ' + filename,myfile)
ftp.quit()
ftp.close()

Solution

  • Your code is currently using ftp.storlines() which is intended for use with ASCII files.

    For binary files such as ZIP files, you need to use ftp.storbinary() instead:

    import ftplib
    
    filename = "test.zip"    
    
    with open(filename, 'rb') as f_upload:
        ftp = ftplib.FTP("ftp.test.com")
        ftp.login('xxxx', 'xxxxx')
        ftp.cwd("public_html/xxx")
        ftp.storbinary('STOR ' + filename, f_upload)
        ftp.quit()
        ftp.close()    
    

    When ASCII mode is used on a ZIP file, it will result in an unusable file which is what you were getting.