开发者

How to use FTPlib in python [closed]

开发者 https://www.devze.com 2023-01-20 16:51 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audien开发者_如何学JAVAce of the internet. For help making this question more broadly applicable, visit the help center. Closed 9 years ago.

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 anonymous@
    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 anonymous@
        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 anonymous@
        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?

0

精彩评论

暂无评论...
验证码 换一张
取 消