Ignore ftplib's 550 error when file does not exist and and continue with other files

Question:

I have problem with ignoring an error and just going on with other commands. The code below is checking if file exists (using FTP.size) and prints message if so. And – here is problem. When it doesn’t find file in this main directory, it should go to /folder2 and look for file here. Instead it throws traceback error (which I "silenced") and doesn’t go to second folder…

from ftplib import FTP
import sys
sys.tracebacklimit = 0


ftp = FTP(host="ip")
loginRepsonse = ftp.login(user='name', passwd='password')
print(loginRepsonse)

fileName = "2022121414040114FTPtestLarge.txt"
# fileName = str(input('What is name of your file? '))

size = ftp.size(fileName)


if isinstance(size, int):
    print("File exists!")
else :    
    ftp.cwd('/folder2')
    if isinstance(size, int):
        print("File exists in another directory!")

When file exists it’s all cool, it shows that file indeed exist, but when not… This error below appears and execution ends, without looking to second folder…

ftplib.error_perm: 550 Could not get file size.

My FTP has only "main" directory and one subfolder – code needs to check two folders (main, then 2nd folder if file wasn’t found). How to ignore this error and continue searching?

Below is whole error output with non-existing file (same happens for EXISTING file, but in different directory, which I can’t access):

230 Login successful.
Traceback (most recent call last):
  File "c:UsersuserDesktopCODES+SCRIPTSftp.py", line 13, in <module>
    size = ftp.size(fileName)
           ^^^^^^^^^^^^^^^^^^
  File "C:UsersuserAppDataLocalProgramsPythonPython311Libftplib.py", line 630, in size
    resp = self.sendcmd('SIZE ' + filename)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:UsersuserAppDataLocalProgramsPythonPython311Libftplib.py", line 281, in sendcmd
    return self.getresp()
           ^^^^^^^^^^^^^^
  File "C:UsersuserAppDataLocalProgramsPythonPython311Libftplib.py", line 254, in getresp
    raise error_perm(resp)
ftplib.error_perm: 550 Could not get file size.

Below is another code I tried:

size = ftp.size(fileName)

from ftplib import FTP, error_perm
try:
    size = ftp.size(fileName)
    print(f"File exists {size}")
    ftp.cwd('/test')          #checks subfolder(or it should..)
    if isinstance(size, int):
         print("File exists in another directory!")
except error_perm as e:
    print(f"File does not exist anywhere: {e}")

This is working (not finished) code based on the answer below.

from ftplib import FTP, error_perm

ftp = FTP(host=host)
loginRepsonse = ftp.login(user=user, passwd=passwd)
print(loginRepsonse)

def repeat():
    fileName = str(input('>>> What is name of your file? n'))
    try:
        size = ftp.size(fileName)
        print(f"File exists in main directory.")
    except error_perm as e:
        pass
        print(f"File does not exist in main directory.")

    try:
        ftp.cwd('/testLAB')
        size = ftp.size(fileName)
        if isinstance(size, int):
                print("File exists in subfolder!")
    except:
        print(f"File does not exist anywhere yet.")

while True:
   repeat()
Asked By: michalb93

||

Answers:

Just catch the appropriate exception:

from ftplib import FTP, error_perm
 
# ...

try:
    size = ftp.size(fileName)
    print(f"File exists {size}")
except error_perm as e:
    print(f"File does not exist (or other error): {e}");
Answered By: Martin Prikryl
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.