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

Bet*_*a_K 0 python directory ftp

好的,所以我必须在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()
Run Code Online (Sandbox Code Playgroud)

joj*_*nas 7

您的代码存在多个问题:首先,filenames数组只包含实际的文件名,而不是整个路径,因此您需要将其加入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()
Run Code Online (Sandbox Code Playgroud)