Upload folders from local system to FTP using Python script

后端 未结 6 1509
花落未央
花落未央 2020-12-09 17:17

I have to automatically upload folders to an FTP using a Python script. I am able to upload a single file, but not folders with subfolders and files in them. I did a lot of

6条回答
  •  春和景丽
    2020-12-09 18:14

    I recently came into this problem and figured out a recursive function to solve it.

    import ftplib
    import os
    
    server = 'localhost'
    username = 'generic_user'
    password = 'password'
    myFTP = ftplib.FTP(server, username, password)
    myPath = r'c:\temp'
    def uploadThis(path):
        files = os.listdir(path)
        os.chdir(path)
        for f in files:
            if os.path.isfile(path + r'\{}'.format(f)):
                fh = open(f, 'rb')
                myFTP.storbinary('STOR %s' % f, fh)
                fh.close()
            elif os.path.isdir(path + r'\{}'.format(f)):
                myFTP.mkd(f)
                myFTP.cwd(f)
                uploadThis(path + r'\{}'.format(f))
        myFTP.cwd('..')
        os.chdir('..')
    uploadThis(myPath) # now call the recursive function            
    

提交回复
热议问题