python ftp方法 - 错误553无法创建文件

时间:2016-02-09 14:33:22

标签: python python-3.x

我使用以下def来上传文件,过程是检查目录是否存在,如果不存在则应该创建它然后上传文件,

我一直收到错误,同时如果我连接到同一个用户并且passwd到ftp我可以创建目录,我使用vsftp作为服务器

    def uploadFTP(filepath, filename_new, env):

    global config

    ftpsrv = config[env]["ftpsrv"]
    ftpusr = config[env]["ftpuser"]
    ftppwd = config[env]["ftppass"]

    filename = os.path.basename(filename_new)
    today = datetime.datetime.now()
    today_path = today.strftime("%Y/%m/%d")
    filename=os.path.join(today_path, filename)
    if not os.path.exists(os.path.join(os.path.dirname(filepath), today_path)):
                os.makedirs(os.path.join(os.path.dirname(filepath), today_path))
    try:
        ftp = ftplib.FTP(ftpsrv)
        ftp.login(ftpusr, ftppwd)
    except:
    logger.error("Ftp connection error has occurred")
        raise
    else:
        f = open(filepath, "r")
        cmd = "STOR %s" %(filename)
        out = ftp.storbinary(cmd, f)
        f.close()
        ftp.quit()
        return out

错误如下:

 File "/usr/lib64/python2.6/ftplib.py", line 218, in getresp
    raise error_perm, resp
error_perm: 553 Could not create file.

这里有任何建议吗?

更新:

将功能修改为以下

def uploadFTP(filepath, filename_new, env):

    global config

    ftpsrv = config[env]["ftpsrv"]
    ftpusr = config[env]["ftpuser"]
    ftppwd = config[env]["ftppass"]

    filename = os.path.basename(filename_new)
    today = datetime.datetime.now()
    today_path = today.strftime("%Y/%m/%d")
    filename=os.path.join(today_path, filename)
    if not os.path.exists(os.path.join(os.path.dirname(filepath), today_path)):
                os.makedirs(os.path.join(os.path.dirname(filepath), today_path))
    try:
        ftp = ftplib.FTP(ftpsrv)
        ftp.login(ftpusr, ftppwd)
    except:
        logger.error("Ftp connection error has occurred")
        raise
    else:
        f = open(filepath, "r")
        ftp.mkd(today_path)
        cmd = "STOR %s" %(filename)
        out = ftp.storbinary(cmd, f)
        f.close()
        ftp.quit()
        return out

我正在

   ftp.mkd(today_path)
  File "/usr/lib64/python2.6/ftplib.py", line 556, in mkd
    resp = self.sendcmd('MKD ' + dirname)
  File "/usr/lib64/python2.6/ftplib.py", line 243, in sendcmd
    return self.getresp()
  File "/usr/lib64/python2.6/ftplib.py", line 218, in getresp
    raise error_perm, resp
error_perm: 550 Create directory operation failed

注意:ftp文件夹中的权限是777并且所有者具有完全读写,如果我通过ftp连接我可以创建文件夹但是通过此功能我不能

请告知

1 个答案:

答案 0 :(得分:0)

您正在将句柄传递给文件夹:

f = open(filepath, "r")

而不是文件的句柄:

f = open(filepath + filename_new, "r")

更新:

您的变量today_path有正斜杠,这表示您要创建子文件夹。您无法使用ftp.mkd直接执行此操作,但是,您可以使用solution中的lecnt

cdTree(today_path)

使用lecnt中的此方法:

def cdTree(currentDir):
    if currentDir != "":
        try:
            ftp.cwd(currentDir)
        except IOError:
            cdTree("/".join(currentDir.split("/")[:-1]))
            ftp.mkd(currentDir)
            ftp.cwd(currentDir)