How to create folder and subfolders if they don't exist with remote send

Question:

I need to send the images downloaded from one server to another. However, I need to save the images in folder with "year" , "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. 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?

Asked By: Prinple Vrlo

||

Answers:

Useful function of the library ftplib:

  • nlst() lists an array for all files in ftp server.
  • mkd() create a folder on the ftp server.

Try the code below (I’m sorry but I didn’t test it):

import ftplib
from datetime import date

year = date.today().year
month = date.today().month

# here I use exactly your example instruction
ftp = ftplib.FTP('ftp-server','userftp','*********')
if year not in ftp.nlst():
  # year directory creation
  ftp.mkd(year)
  # year/month directory creation
  ftp.mkd(year + "/" + month)
else:
  if month not in ftp.nlst(year):
      # year/month directory creation
      ftp.mkd(year + "/" + month)

See this link for info about ftplib.

Answered By: frankfalse