How to use FTPlib in python – Education Career Blog

i’m writing an application that is supposed to upload a file to an FTP server.

Here’s the code:

    try:
        f = open(filename,"rb")
    except:
        print "error 0"
    try:
        ftp = FTP(str(self.ConfigUri))
        print "CONNECTED!"
    except:
        print "CANNOT CONNECT"
    try:
        ftp = FTP(str(self.ConfigUri))   # connect to host, default port
    except:
        print "error 1"
    try:
        ftp.login()               # user anonymous, passwd [email protected]
    except:
        print "error2"
    try:
        ftp.storbinary('STOR ' + filename, f)
    except:
        print "error 3"
    try:
        ftp.quit()
    except:
        print "error 4"

I am getting an error at ftp.storbinary(‘STOR ‘ + filename, f). Any ideas why?

,

It could be that the filename is the full path, you should use the basename instead:

import os
folder, base = os.path.split(filename)
ftp.storbinary('STOR ' + base, f)

If not make sure your python is running at the right place:

import os
print os.getcwd()

,

It looks like you are passing a full path to open the file and you are using that same full path to name the file for ftplib. Instead, cd to that directory and name the file with just the file name.

Stealing @eumiro’s code:

from ftplib import FTP
import os.path

try:
    with open(fullpath,"rb") as f:
        directory, filename = os.path.split(fullpath)
        ftp = FTP(str(self.ConfigUri))   # connect to host, default port
        ftp.login()               # user anonymous, passwd [email protected]
        ftp.cwd(directory)
        ftp.storbinary('STOR ' + filename, f)
        ftp.quit()
except Exception, e:
    print e

If the directory is not on the server, you can make it:

ftp.mkd(directory)

Or you can omit the ftp.cwd() call and just place the file in the ftp root.

,

What error does the following code report?

try:
    with open(filename,"rb") as f:
        ftp = FTP(str(self.ConfigUri))   # connect to host, default port
        ftp.login()               # user anonymous, passwd [email protected]
        ftp.storbinary('STOR ' + filename, f)
        ftp.quit()
except Exception, e:
    print e

EDIT:
Error 550? Looks like access denied error… Does anonymous user have the rights to write into that FTP directory?

Leave a Comment