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

Time:10-26

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?

CodePudding user response:

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 datetime

ftp = ftplib.FTP('ftp-server','userftp','*********')
dir_timestamp=datetime.now().strftime('%Y-%m')
if dir_timestamp not in ftp.nlst():
  ftp.mkd(dir_timestamp)

See this link for info about ftplib.

  • Related