使用Python和ftplib上传整个目录

1 投票
1 回答
3368 浏览
提问于 2025-04-17 22:05

我想用Python和ftplib把整个文件夹上传到服务器。

template_dir = '/Users/seb/projects/citats/static/templates/blanka/'

for root, dirs, files in os.walk(template_dir, topdown=True):
    relative = root[len(template_dir):].lstrip(os.sep)
    for d in dirs:
        ftp.mkd(os.path.join(relative, d))

    for f in files:
        ftp.cwd(relative)
        ftp.storbinary('STOR ' + f, open(os.path.join(template_dir, relative, f), 'rb'))
        ftp.cwd('/')

ftp.quit()

这个方法运行得不错,但我觉得还有很多可以改进的地方(特别是处理文件的那部分)。你能给我一些建议吗?

1 个回答

1

你没有关闭你的文件

for f in files:
    filePath = os.path.join(template_dir,relative,f)
    ftp.cwd(relative)
    with open(filePath, 'rb') as fileObj:
        ftp.storbinary('STOR '+f,fileObj)
    ftp.cwd('/')

对于那些不知道的人,'with open(file_path, mode) as f:' 这种写法会在缩进回到 'with' 的地方时自动关闭文件。

撰写回答