python ftp方法错误553无法创建fi

2024-09-30 04:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果我用ftp连接服务器,我可以用ftp创建相同的目录

    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

错误如下:

^{pr2}$

有什么建议吗?在

更新:

修改函数如下

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连接,我可以创建文件夹,但通过这个功能我不能

请告知


Tags: pathenvconfignewtodayosftperror
1条回答
网友
1楼 · 发布于 2024-09-30 04:35:37

您正在向文件夹传递句柄:

f = open(filepath, "r")

而不是文件的句柄:

^{pr2}$

更新:

您的变量today_path有正斜杠,这表明您想要创建子文件夹。您不能直接使用ftp.mkd来执行此操作,但是可以使用来自lecntsolution

cdTree(今天的路径)

lecnt使用此方法:

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

相关问题 更多 >

    热门问题