Reputation: 2064
i try to upload a whole directory to a server using python and 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()
This solution works fine but in my opinion it could be widely improved (especially the file loop). Can you advice me ?
Upvotes: 1
Views: 3391
Reputation: 11
you did not close your files
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('/')
for those who don't know, the 'with open(file_path,mode) as f:' syntax automatically closes files when the indent aligns back with 'with'
Upvotes: 1