使用Python和ftplib上传整个目录
我尝试使用python和ftplib将整个目录上载到服务器使用Python和ftplib上传整个目录,python,ftp,Python,Ftp,我尝试使用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.mk
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()
这个解决方案工作得很好,但我认为它可以得到广泛的改进(尤其是文件循环)。
你能告诉我吗?你没有关闭你的文件
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”对齐时自动关闭文件。您的代码似乎没有特别的问题,正如您所说的,您的解决方案工作得很好。我建议你把这个问题转移到你可以继续问下去,但首先你要澄清你想要改进的地方。