Search code examples
pythonpython-3.xpython-2.7ftplib

How to create folders and subfolders into a remote FTP server if they don't exist


I need to send the images downloaded from one server to another. Furthermore, I would like to save images in folders organized by date with "year" and "month". Here's an example:

ftp = ftplib.FTP('ftp-server','userftp','*********')
    
file = open('download-torrent-filme.webp','rb')
    
ftp.storbinary('STOR year/month/download-torrent-filme.webp', file)

I need to create such folders in case they don't exist on the FTP server. My idea is to store the year and month in a variable and send it. For example:

year = date.today().year
    
month = date.today().month
    
ftp.storbinary('STOR '+year+'/'+month+'/download-torrent-filme.webp', file)

But I need the folder to be created if it doesn't exist. How can I do this cleanly and simply as possible?


Solution

  • To solve your tasks you can use following 2 functions of the library ftplib:

    • nlst(): returns a list with all files and directory present on the FTP server
    • mkd(): create a folder on the filesystem of the FTP server.

    Try the code below:

    import ftplib
    from datetime import date
    
    str_year = str(date.today().year)
    str_month = str(date.today().month)
    
    # here I use exactly your example instruction
    ftp = ftplib.FTP('ftp-server','userftp','*********')
    if str_year not in ftp.nlst():
        # year directory creation
        print(f"[1] - {str_year} directory creation")
        ftp.mkd(str_year)
        # year/month directory creation
        print(f"[1] - {str_year}/{str_month} directory creation")
        ftp.mkd(str_year + "/" + str_month)
    else:
        if str_year + '/' + str_month not in ftp.nlst(str_year):
            print(f"[2] - {str_year}/{str_month} directory creation")
            # year/month directory creation
            ftp.mkd(str_year + "/" + str_month)
    

    Documentation