Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python FTP download file with certain name

Tags:

python

I have this FTP with folder and it contains these files:

pw201602042000.nc,
 pw201602042010.nc,
 pw201602042020.nc, 
 pw201602042030.nc, 
 pw201602042040.nc,
 pw201602042050.nc,
 pw201602042100.nc,
 pw201602042110.nc, 
 pw201602042120.nc, 
 pw201602042130.nc, 
 pw201602042140.nc,
 pw201602042150.nc, 
 pw201602042200.nc

how to download only file ending with 00?

from ftplib import FTP

server = FTP("ip/serveradress")
server.login("user", "password")

server.retrlines("LIST") 
server.cwd("Folder")

server.sendcmd("TYPE i") # ready for file transfer
server.retrbinary("RETR %s"%("pw201602042300.nc"), open("pw", "wb").write) 
like image 520
hananoorr Avatar asked Jul 19 '26 20:07

hananoorr


1 Answers

when you obtained the list of files as list_of_files, just use fnmatch to match the file names according to wildcard:

list_of_files = server.retrlines("LIST")
dest_dir = "."
for name in list_of_files:
    if fnmatch.fnmatch(name,"*00.nc"):
        with open(os.path.join(dest_dir,name), "wb") as f:
            server.retrbinary("RETR {}".format(name), f.write)  

(note that you're writing the files on the same "pw" output file, I changed that, reusing the original name and provided a destination directory variable, and protecting the open in a with block to ensure file is closed when exiting the block)

like image 187
Jean-François Fabre Avatar answered Jul 28 '26 17:07

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!