schnarkle
schnarkle

Reputation: 15

Using python to FTP download files with specific dates in filename?

I'm trying to write a python script to download comics from a repository that has files named as such:

ba220627.tif
ba220628.tif
ba220629.tif
ba220701.tif
ba220702.tif
ba220703.tif

Say I want to download the next 7 days worth of files..

I've got the portion to log in through ftp... I'm assuming I will use timedelta to calculate the days?
Where I'm stuck is how to put the filename in a string with the correct date calculations for the filename?

Or am I going about this all wrong?

Thanks Sean C! If it comes across a "file not found" the script dies. How can I make it skip and continue? Example some of these don't run on Sundays so those would not be there....

Upvotes: 0

Views: 337

Answers (1)

Sean C
Sean C

Reputation: 181

the first part of main generates the filenames and adds them to the dates list:

import datetime as dt
from ftplib import FTP

HOSTNAME = 'x'
USERNAME = 'y'
PASSWORD = 'z'


def get_baldy(fn, ftp):
    ftp.cwd("/Comic_Strips/Baldy")
    with open(fn, "wb") as ofile:
        ftp.retrbinary("RETR " + fn, ofile.write)


def main():
    today = dt.date.today()  # create a datetime.date object for today
    dates = []

    for n in range(7):
        target_date = today + dt.timedelta(days=n)  # add the timedelta to today
        target_date_str = str(target_date)[2:].replace('-', '')  # tidy the str
        dates.append(f'ba{target_date_str}.tif')
    print(dates)
    
    ftp = FTP(HOSTNAME, USERNAME, PASSWORD)
    ftp.login()  # added
    for cname in dates:
        get_baldy(cname, ftp)


if __name__ == '__main__':

    main() 

print dates output:

['ba220621.tif', 'ba220622.tif', 'ba220623.tif', 'ba220624.tif', 'ba220625.tif', 'ba220626.tif', 'ba220627.tif']

Upvotes: 1

Related Questions