1

can you pls shed some light on what I am doing wrong here... I'm a Python newby... This connects and I can get a list of files in a FTP specific directory, but for the love of BigBang.. It isn't downloading any files. I need to download files starting with a specific Name string:

from ftplib import FTP_TLS
import fnmatch
import os

ftps = FTP_TLS('myftp_site.com')
ftps.login('userxx', 'pwxx')
ftps.prot_p()
ftps.cwd('Inbox')

print("File list:")

list_of_files = ftps.retrlines("LIST")
dest_dir = "C:\DownloadingDirectory"

for name in list_of_files:
    if fnmatch.fnmatch(name,"StartingFileName*"):
        with open(os.path.join(dest_dir, name), "wb") as f:
            ftps.retrbinary("RETR {}".format(name), f.write)

ftps.quit()

    enter code here
Anand Bhat
  • 5,591
  • 26
  • 30
  • Print out what you get and see if the data looks reasonable. You likely want `"NLST"` instead of`"LIST"`. – tdelaney Apr 21 '17 at 18:54
  • thx @tdelaney I tried NLST instead of LIST, but the files aren't transferring to my destination directory. Print does return the files from the repository I want to retrieve them from, but I just cannot get them to transfer.. – AstroBernal Apr 21 '17 at 19:49
  • Have you tried `PROMPT OFF` followed by `MGET PATTERN*`? – Mark Setchell Apr 21 '17 at 20:13
  • @MarkSetchell thx, haven't tried PROMPT OFF, honestly I am unaware of it, getting my feet soaked in Py ... tdelaney's updated code below worked like a charm, but I am also open to trying out any other methods. I welcome anything you'd like to expand on. Thx – AstroBernal Apr 21 '17 at 20:19

1 Answers1

3

You are having problems getting the file list. LIST returns a long-format listing with file attributes like for instance

-rw-------   1 td       dialout       543 Apr  3 20:18 .bash_history

Use NLST to get a short list. Also, the retrlines() function is kinda strange. It calls a callback for each line (defaulting to print) it receives. The command only returns a status string. You can add your own callback to fill a list, or use the .nlst() command to get the list for you.

from ftplib import FTP_TLS
import fnmatch
import os

ftps = FTP_TLS('myftp_site.com')
ftps.login('userxx', 'pwxx')
ftps.prot_p()
ftps.cwd('Inbox')

print("File list:")

list_of_files = []
ftps.retrlines("NLST", list_of_files.append)
# ...or use the existing helper
# list_of_files = ftps.nlst()

dest_dir = "C:\DownloadingDirectory"

for name in list_of_files:
    if fnmatch.fnmatch(name,"StartingFileName*"):
        with open(os.path.join(dest_dir, name), "wb") as f:
            ftps.retrbinary("RETR {}".format(name), f.write)

ftps.quit()
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 1
    THANK YOU! it worked like a charm. I really appreciate you helping me out. Have a great weekend. Regarding the difference between NLST and LIST, you're absolutely right, LIST includes a ton of attributes, but NLST simply returns file names only. Thanks again, @tdelaney ! – AstroBernal Apr 21 '17 at 20:20