Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to download specified extension type of files from FTP server using python

I am trying to download each .txt file from my FTP server using python but as of now I only have one file being downloaded that is specified by it’s name. Does anyone know the way I can change it to download all of the .txt files from my server?

    # connect to the FTP server
    ftp = FTP(FTP_HOST, FTP_USER, FTP_PASS)

    ftp.encoding = "utf-8"

    ftp.cwd('/files')
    ftp.retrlines('LIST')

    with open('test.txt', 'wb') as fp:
        ftp.retrbinary('RETR test.txt', fp.write)

    ftp.quit()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Something like this should work fine:

import fnmatch

with FTP(FTP_HOST,FTP_USER,FTP_PASS) as ftp:
        ftp.encoding = "utf-8"
        ftp.cwd('/files')
        for filename in ftp.nlst():
            if fnmatch.fnmatch(filename, '*.txt'):
                 with open(filename, 'wb') as fp:
                      ftp.retrbinary(f'RETR {filename}', fp.write)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading