ftputil判断FTP文件夹存在时isExist恒为False报错问题
问题描述
我编写for循环遍历FTP指定目录下的文件,实现目标文件夹不存在则自动创建的逻辑,初始代码如下:
import ftputil host=ftputil.FTPHost('x.x.x.x',"x","x") # 连接到ftp服务器 mypathexist='./CameraOld' # 目标路径实际位置为/opt/Camera/CameraOld mypath = '.' # 默认工作路径为/opt/Camera host.chdir(mypath) files = host.listdir(host.curdir) for f in files: # 遍历当前目录下的文件 if f==mypathexist: # 判断是否存在名为CameraOld的文件夹 isExist=True break else: isExist=False # 未匹配到则标记为不存在 print(isExist) if isExist==False: # 文件夹不存在时创建 host.mkdir(mypathexist) else: print("ok")
运行时isExist变量取值始终为False,脚本会尝试创建已经存在的文件夹,抛出如下报错:
False #isExist打印结果 Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/ftputil/host.py", line 695, in command self._session.mkd(path) File "/usr/lib/python3.10/ftplib.py", line 637, in mkd resp = self.voidcmd('MKD ' + dirname) File "/usr/lib/python3.10/ftplib.py", line 286, in voidcmd return self.voidresp() File "/usr/lib/python3.10/ftplib.py", line 259, in voidresp resp = self.getresp() File "/usr/lib/python3.10/ftplib.py", line 254, in getresp raise error_perm(resp) ftplib.error_perm: 550 CameraOld: file exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/Bureau/try.py", line 16, in <module> host.mkdir(mypathexist) File "/usr/local/lib/python3.10/dist-packages/ftputil/host.py", line 697, in mkdir self._robust_ftp_command(command, path) File "/usr/local/lib/python3.10/dist-packages/ftputil/host.py", line 656, in _robust_ftp_command return command(self, tail) File "/usr/local/lib/python3.10/dist-packages/ftputil/host.py", line 694, in command with ftputil.error.ftplib_error_to_ftp_os_error: File "/usr/local/lib/python3.10/dist-packages/ftputil/error.py", line 195, in __exit__ raise PermanentError( ftputil.error.PermanentError: 550 CameraOld: file exist Debugging info: ftputil 5.0.4, Python 3.10.4 (linux)
问题根因
- 路径字符串不匹配:
host.listdir(host.curdir)返回的是当前目录下文件/文件夹的纯名称,不带./前缀,定义的mypathexist值为./CameraOld,和实际返回的名称CameraOld做相等判断永远不会成立。 - 循环逻辑错误:循环的
else分支每次不匹配都会把isExist赋值为False,就算后续匹配到目标文件夹,只要遍历到其他文件就会覆盖之前的标记结果;且isExist没有提前初始化,如果目录为空会直接抛出变量未定义的错误。 - 语法错误:初始代码中
mypathexist定义行后直接追加说明内容,没有加#注释标记,运行时会直接报语法错误。
修复方案
ftputil自带路径存在判断的内置方法,无需手动遍历目录做判断,逻辑更简洁可靠,修复后代码如下:
import ftputil host = ftputil.FTPHost('x.x.x.x', "x", "x") # 连接FTP服务器 target_dir = 'CameraOld' # 切换到默认工作路径/opt/Camera host.chdir('.') # 调用内置方法判断路径是否存在 if not host.path.exists(target_dir): host.mkdir(target_dir) else: print("ok")
如果坚持使用手动遍历的实现方式,需要做两处修正:一是将mypathexist的值改为不带前缀的CameraOld;二是在循环前先初始化isExist = False,仅在匹配到目标名称时将其设为True并跳出循环,不要在循环else分支反复赋值。
内容的提问来源于stack exchange,提问作者El Santo
相关产品推荐
相关产品推荐

