Jecki February 2016

python - Ftp upload file in directory structure per /year/month/day

I'm using the following function to upload files and structure per week day ,

what i'm looking to adjust here to change the directory structure to be per year/month/day

example /Incoming/2016/02/08/filename

if the dir or sub dir is not exits it will create it then upload

which method should be use to switch from per week day to deep dir structure per year/month/day

def dir_today ():
    """ Function to determine directory today """
    week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    day = week[datetime.today().weekday()]
    return day

def ftp_upload (ifn):
        """" FTP upload Function. Destination file will be appended with date and timecode received from meta data"""
        src = "%s/%s" % (src_loc,ifn)
        try:
                create_time = get_meta(ifn)
        except:
                create_time = datetime.now().strftime("VID_%Y-%m-%d_T_%H-%M-%S")
        dst_file = os.path.splitext(ifn)[0] + os.path.splitext(ifn)[1]
        upload_directory = ftp_base_directory + '/' + dir_today() + '/'

        try:
                ftp_connect = ftplib.FTP(ftp_server, ftp_login, ftp_password)

                try:
                        ftp_connect.cwd(upload_directory)
                except ftplib.all_errors:
                        ftp_connect.mkd(upload_directory)
                        ftp_connect.cwd(upload_directory)

                file = open(src, "rb")
                send = ftp_connect.storbinary("STOR "+ dst_file, file)
                ftp_connect.close
                file.close()
                os.remove(src)

                logger.info("Moved file %s" %(src))

                oflist.remove(ifn)
                hsize.pop(ifn)
                uploaded.insert(0,ifn)
                try:
                        uploaded.pop(9)
                except:
                        pass
        except Exception as e:
                logger.info("Error: %s" %(repr(        

Answers


keithb February 2016

You could just modify dir_today() to return the subpath:

def dir_today():
    today = date.today()
    return '{day.year}/{day.month}/{day.day}'.format(day=today)


Rolf of Saxony February 2016

Or alternatively:

>>> def dir_today():
...  return datetime.datetime.today().strftime("%Y/%m/%d")
... 
>>> dir_today()
'2016/02/08'

Post Status

Asked in February 2016
Viewed 1,150 times
Voted 4
Answered 2 times

Search




Leave an answer