ftplib.error_perm: 500 not understood downloading file from ftp

Question:

I am newbie to python and trying to download all csv files from a ftp folder but I receive this error.
this is my code:

ftp = ftplib.FTP('192.128.0.20', 'bingo', 'Password')
ftp.cwd('/')
filematch = '*.csv'


for filename in ftp.nlst(filematch):
    fhandle = open(filename,'wb')
    ftp.retrbinary('RETR' + filename, fhandle.write)
    fhandle.close()

this is my error:

 Traceback (most recent call last):
      File "./dirmon.py", line 65, in <module>
        ftp.retrbinary('RETR' + filename, fhandle.write)
      File "/usr/lib/python2.7/ftplib.py", line 406, in retrbinary
        conn = self.transfercmd(cmd, rest)
      File "/usr/lib/python2.7/ftplib.py", line 368, in transfercmd
        return self.ntransfercmd(cmd, rest)[0]
      File "/usr/lib/python2.7/ftplib.py", line 331, in ntransfercmd
        resp = self.sendcmd(cmd)
      File "/usr/lib/python2.7/ftplib.py", line 244, in sendcmd
        return self.getresp()
      File "/usr/lib/python2.7/ftplib.py", line 219, in getresp
        raise error_perm, resp
    ftplib.error_perm: 500 RETRRINGGODATA-2014-07-02.CSV not understood
Asked By: shriyaj

||

Answers:

missing space at ftp.retrbinary: (I also prfer with statement):

ftp = ftplib.FTP('192.128.0.20', 'bingo', 'Password')
ftp.cwd('/')
filematch = '*.csv'
target_dir = '/home/toor/ringolist'
import os

for filename in ftp.nlst(filematch):
    target_file_name = os.path.join(target_dir, os.path.basename(filename))
    with open(target_file_name ,'wb') as fhandle:
        ftp.retrbinary('RETR %s' % filename, fhandle.write)
Answered By: WBAR

Use this:

ftp.encoding = "utf-8"

And try to change:

ftp.retrbinary('RETR %s' % filename, fhandle.write)

to:

ftp.retrbinary(f"RETR {filename}", fhandle.write)

It works for me.

Source: https://www.thepythoncode.com/article/download-and-upload-files-in-ftp-server-using-python

Answered By: Marrom Ed
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.