How to pull all files from ftp link

How to pull all files from ftp link
Tagged:

Best Answer

  • @Shalini.YPatted

    I assumed that you would like to download all files and all folders from the FTP server.

    In Python, you can use the ftplib library.

    The code looks like this:

    import ftplib
    import os
    local_path = []
    ftp = ftplib.FTP("FTP Server")
    ftp.login("username","password")
    ## Function ###
    def downloadfiles(directory):
        global local_path
        print("Download files from ",directory)
        if directory!='.':
            local_path.append(directory)
        if(len(local_path) != 0): 
            joined_str = "\\".join(local_path)
            if os.path.exists(joined_str) == False:
                print("Create a local directory ", joined_str)
                os.makedirs(joined_str)
        ftp.cwd(directory)
        for name, facts in ftp.mlsd():
            if(facts["type"] == 'dir'):
                downloadfiles(name)
            if(facts["type"] == 'file'):
                print("Download a file ", name)
                ftp.retrbinary("RETR "+name, open(joined_str+"\\"+name, 'wb').write)
        if len(local_path) != 0:
            local_path.pop()
        if ftp.pwd() != '/':
            ftp.cwd("..")
    ## End Function ##
    downloadfiles(".")
    ftp.close()

    This is just a sample code. Please test it thoroughly before using it in production.

Answers