import os import os.path import datetime import config from ftplib import FTP import shutil if os.name =='nt': root = "//WDsentinel/share/Daily" elif os.name == 'posix': root = '/home/share/Daily' startdate = datetime.date.today() for i in range(10): workdate = startdate - datetime.timedelta(days=i) workdatestr = str(workdate) try: filelist = [(f, os.stat(os.path.join(root, workdatestr, f)).st_ctime) \ for f in os.listdir(os.path.join(root, workdatestr)) if f.startswith("securitiesNpv")] except OSError: continue filelist = sorted(filelist, key = lambda x: x[1], reverse = True) if filelist: file_to_upload = filelist[0][0] newfile_to_upload = file_to_upload if workdate < startdate: newfile_to_upload = "securitiesNpv{0}.csv".format( datetime.datetime.strftime(datetime.datetime.today(), "%Y%m%d_%H%M%S")) # due to the way the drive is mounted, we get an exception when copy # tries to change permissions try: shutil.copy(os.path.join(root, workdatestr, file_to_upload), os.path.join(root, str(startdate), newfile_to_upload)) except OSError: pass print("moved file from {0}".format(workdatestr)) ftp = FTP('ftp.globeop.com') ftp.login('srntsftp', config.ftp_password) ftp.cwd('incoming') with open(os.path.join(root, str(startdate), newfile_to_upload), "rb") as fh: ftp.storbinary('STOR ' + newfile_to_upload, fh) break print("done")