1

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 ?

2
  • You don't seem to have a particular problem with your code, as you say your solution works fine. I suggest you move this question to codereview.stackexchange.com
    – msvalkon
    Mar 13, 2014 at 9:22
  • You could ask this on Code Review, but first you'll want to clarify what you're looking to improve.
    – Shog9
    Mar 26, 2014 at 0:08

1 Answer 1

1

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.