Derek Connolly
Derek Connolly

Reputation: 3

Python download a file from FTP where the filename starts with specific characters

I am trying to write a python script that will login to an FTP server and download only files in a directory where the filenames start with certain characters. The FTP directory I am connecting to has files that all have different filenames and all end in date/timestamps, not a file extension like ".txt". For example:

-rw-------   1 USERNAME USERNAME      1230456 Jul 18 11:02 NOTMYFILE.FILE.201807181102
-rw-------   1 USERNAME USERNAME      1230457 Jul 18 12:02 FILEINEED.FILE.201807181202
-rw-------   1 USERNAME USERNAME      1230458 Jul 18 10:02 FILEINEED.FILE.201807181002
-rw-------   1 USERNAME USERNAME      1230458 Jul 18 09:02 NOTMYFILE.FILE.201807181902

I need to tell python only to download the files that start with "FILEINEED".

I have searched and not been able to find a way to download a file where the filename starts with 'FILEINEED' and have it ignore the files that start with 'NOTMYFILE'

Below is what I have so far in my script:

from ftplib import FTP

ftp = FTP("ftp.server.url")
ftp.login(user="UserName", passwd="password123")
ftp.retrlines("LIST")

ftp.cwd("/outbox/")

Any help is appreciated!

Upvotes: 0

Views: 3604

Answers (2)

Brijesh Rana
Brijesh Rana

Reputation: 651

There are three steps in this -

  1. Connect with FTP
  2. Get all Files name from FTP
  3. Search your file with specific character that you want to download

Code is written below -

#Open ftp connection
ftp = ftplib.FTP('ftp address', 'Username','Password')
# Get All Files
files = ftp.nlst()
for file in files:
  if(file.startswith('abc') and file.endswith('.xyz')):
    print("Downloading..." + file)
    ftp.retrbinary("RETR " + file ,open("D:/" + file, 'wb').write)

Or we can search specific character in the file name like this also -

if 'abxy' in file:
    print(file)
    ftp.retrbinary("RETR " + file ,open("D:/" + file, 'wb').write)

Upvotes: 1

You could get a list of all the filenames, filter that list by 'FILEINEED' in filename, then FTP.retrbinary on those files:

filesineed = [filename for filename in ftp.nlst() if 'FILEINEED' in filename]

# Iterate through all the filenames and retrieve them one at a time
for filename in filesineed:
    local_filename = os.path.join(os.getcwd(), filename)
    with open(local_filename, 'wb') as f:
        print('downloading {}...'.format(filename))
        ftp.retrbinary('RETR %s' % filename, f.write)

will save those files to your local current working directory. Change local_filename if you want to save elsewhere.

Upvotes: 1

Related Questions