You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

忽略ftplib的550错误,实现多FTP目录文件存在性检查

问题:忽略FTP文件检查错误并继续执行后续目录查找

我需要实现的逻辑是:先检查FTP主目录是否存在目标文件,若不存在则进入子目录/folder2继续查找。但当前代码在主目录找不到文件时,会直接抛出ftplib.error_perm: 550 Could not get file size.错误并终止程序,无法执行后续的子目录检查。

原始代码

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!")

错误现象

当文件不存在于主目录时,程序直接终止并抛出以下错误:

ftplib.error_perm: 550 Could not get file size.

完整错误输出:

230 Login successful.
Traceback (most recent call last):
  File "c:\Users\user\Desktop\CODES+SCRIPTS\ftp.py", line 13, in <module>
    size = ftp.size(fileName)
           ^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\ftplib.py", line 630, in size
    resp = self.sendcmd('SIZE ' + filename)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\ftplib.py", line 281, in sendcmd
    return self.getresp()
           ^^^^^^^^^^^^^^
  File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\ftplib.py", line 254, in getresp
    raise error_perm(resp)
ftplib.error_perm: 550 Could not get file size.

我尝试过的代码

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}")

基于回答编写的未完成可运行代码

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()

解决方案

核心问题是ftp.size()在文件不存在时会直接抛出异常,而非返回非整数值,因此你的if isinstance(size, int)逻辑根本没机会执行。正确的做法是用try-except块分别捕获每个目录的检查异常,同时注意切换目录后要切回主目录,避免影响后续查询的目录位置。

修改后的完整可运行代码:

from ftplib import FTP, error_perm

# 初始化FTP连接
ftp = FTP(host="ip")
login_response = ftp.login(user='name', passwd='password')
print(login_response)

def check_file_exists(file_name):
    # 检查主目录
    try:
        ftp.size(file_name)
        print(f"文件 {file_name} 存在于主目录")
        return True
    except error_perm:
        print(f"文件 {file_name} 不存在于主目录")
    
    # 切换到子目录检查
    try:
        ftp.cwd('/folder2')
        ftp.size(file_name)
        print(f"文件 {file_name} 存在于子目录 /folder2")
        return True
    except error_perm:
        print(f"文件 {file_name} 不存在于子目录 /folder2")
    finally:
        # 无论子目录检查成功与否,强制切回主目录,避免影响后续操作
        ftp.cwd('/')
    
    # 两个目录都未找到文件
    print(f"文件 {file_name} 在所有目录中均不存在")
    return False

# 目标文件名,可替换为输入交互
file_name = "2022121414040114FTPtestLarge.txt"
# file_name = input("请输入要查找的文件名:")
check_file_exists(file_name)

# 关闭FTP连接
ftp.quit()

关键改进点

  • 用try-except分别包裹每个目录的ftp.size()调用,精准捕获error_perm异常,避免程序终止
  • 通过finally块确保子目录检查后切回主目录,防止后续操作的目录位置错误
  • 拆分检查逻辑为独立函数,代码结构更清晰、易维护
  • 增加返回值,方便后续扩展业务逻辑

内容的提问来源于stack exchange,提问作者michalb93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:25:09