Upload folders from local system to FTP using Python script

后端 未结 6 1508
花落未央
花落未央 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:15

    EDIT 20/12/2017:

    I have written a project in GitHub for this purpose. Click for details!


    There are good answers above but i also want to add a good one using ftputil package. If you need to upload files from local directory to ftp directory, you can use this recursive function:

    def upload_dir(localDir, ftpDir):
    list = os.listdir(localDir)
    for fname in list:
        if os.path.isdir(localDir + fname):             
            if(ftp_host.path.exists(ftpDir + fname) != True):                   
                ftp_host.mkdir(ftpDir + fname)
                print(ftpDir + fname + " is created.")
            upload_dir(localDir + fname + "/", ftpDir + fname + "/")
        else:               
            if(ftp_host.upload_if_newer(localDir + fname, ftpDir + fname)):
                print(ftpDir + fname + " is uploaded.")
            else:
                print(localDir + fname + " has already been uploaded.")
    

    If you decide to use this function, you have to connect ftp using ftputil package. For this, you can use this snippet:

    with ftputil.FTPHost("ftp_host", "ftp_username", "ftp_password") as ftp_host:
    

    So, we're almost done. The last thing is usage of the function for beginners like me:

    local_dir = "D:/Projects/.../"
    ftp_dir = "/.../../"
    
    upload_dir(local_dir, ftp_dir)
    

    The most important thing is "/" character at the end of paths. You need to put it at the end. Finally, i want to share entire code:

    with ftputil.FTPHost("ftp_host", "ftp_username", "ftp_password") as ftp_host:
        def upload_dir(localDir, ftpDir):
        list = os.listdir(localDir)
        for fname in list:
            if os.path.isdir(localDir + fname):             
                if(ftp_host.path.exists(ftpDir + fname) != True):                   
                    ftp_host.mkdir(ftpDir + fname)
                    print(ftpDir + fname + " is created.")
                upload_dir(localDir + fname + "/", ftpDir + fname + "/")
            else:               
                if(ftp_host.upload_if_newer(localDir + fname, ftpDir + fname)):
                    print(ftpDir + fname + " is uploaded.")
                else:
                    print(localDir + fname + " has already been uploaded.")
        local_dir = "D:/Projects/.../"
        ftp_dir = "/.../../"
    
        upload_dir(local_dir, ftp_dir)
    

提交回复
热议问题