在python中如何在FTP上上载完整目录?

在python中如何在FTP上上载完整目录?,python,ftp,directory,Python,Ftp,Directory,好的,我必须上传一个目录,里面有子目录和文件,在FTP服务器上。但我似乎不能把它弄对。我想上传的目录,因为它是,它的子目录和文件的地方 ftp = FTP() ftp.connect('host',port) ftp.login('user','pass') filenameCV = "directorypath" def placeFiles(): for root,dirnames,filenames in os.walk(filenameCV): for files in f

好的,我必须上传一个目录,里面有子目录和文件,在FTP服务器上。但我似乎不能把它弄对。我想上传的目录,因为它是,它的子目录和文件的地方

ftp = FTP()
ftp.connect('host',port)
ftp.login('user','pass')
filenameCV = "directorypath"

def placeFiles():

 for root,dirnames,filenames in os.walk(filenameCV):
    for files in filenames:
        print(files)
        ftp.storbinary('STOR ' + files, open(files,'rb'))
        ftp.quit()

placeFiles()

您的代码存在多个问题:首先,
文件名
数组将只包含实际的文件名,而不是整个路径,因此您需要使用
fullpath=os.path.join(root,files)
将其连接起来,然后使用
open(fullpath)
。其次,退出循环内的FTP连接,将
FTP.quit()
移动到
placeFiles()函数的级别

要递归地上载目录,您必须遍历根目录,同时遍历远程目录,随时上载文件

完整示例代码:

import os.path, os
from ftplib import FTP, error_perm

host = 'localhost'
port = 21

ftp = FTP()
ftp.connect(host,port)
ftp.login('user','pass')
filenameCV = "directorypath"

def placeFiles(ftp, path):
    for name in os.listdir(path):
        localpath = os.path.join(path, name)
        if os.path.isfile(localpath):
            print("STOR", name, localpath)
            ftp.storbinary('STOR ' + name, open(localpath,'rb'))
        elif os.path.isdir(localpath):
            print("MKD", name)

            try:
                ftp.mkd(name)

            # ignore "directory already exists"
            except error_perm as e:
                if not e.args[0].startswith('550'): 
                    raise

            print("CWD", name)
            ftp.cwd(name)
            placeFiles(ftp, localpath)           
            print("CWD", "..")
            ftp.cwd("..")

placeFiles(ftp, filenameCV)

ftp.quit()

您是希望所有文件都在一个目录中,还是希望递归地复制这些目录?请看我的示例。我假设
directorypath
是您的本地基本目录,您可以将所有内容上载到FTP服务器的根目录。否则你必须在上传之前添加一个
ftp.cwd(…)
。很好的解决方案,我几乎可以从头开始使用它