如何让Python检查FTP目录是否存在?

21 投票
8 回答
50859 浏览
提问于 2025-04-15 12:46

我正在使用这个脚本连接到一个示例的FTP服务器,并列出可用的目录:

from ftplib import FTP
ftp = FTP('ftp.cwi.nl')   # connect to host, default port (some example server, i'll use other one)
ftp.login()               # user anonymous, passwd anonymous@
ftp.retrlines('LIST')     # list directory contents
ftp.quit()

我该如何利用ftp.retrlines('LIST')的输出结果来检查某个目录(比如public_html)是否存在?如果存在,就切换到那个目录,然后执行其他代码并退出;如果不存在,就直接执行代码并退出?

8 个回答

5

你可以通过控制连接发送“MLST path”命令。这样会返回一行信息,其中包含路径的类型(注意这里有'type=dir'):

250-Listing "/home/user":
 modify=20131113091701;perm=el;size=4096;type=dir;unique=813gc0004; /
250 End MLST.

如果用Python来写,代码大概是这样的:

import ftplib
ftp = ftplib.FTP()
ftp.connect('ftp.somedomain.com', 21)
ftp.login()
resp = ftp.sendcmd('MLST pathname')
if 'type=dir;' in resp:
    # it should be a directory
    pass

当然,上面的代码并不是百分之百可靠的,还是需要一个“真正的”解析器。你可以看看ftplib.py中MLSD命令的实现,它和MLST很相似(MLSD和MLST的区别在于,MLSD的响应是通过数据连接发送的,但传输的行格式是一样的):http://hg.python.org/cpython/file/8af2dc11464f/Lib/ftplib.py#l577

11

你可以使用一个列表。比如说:

import ftplib
server="localhost"
user="user"
password="test@email.com"
try:
    ftp = ftplib.FTP(server)    
    ftp.login(user,password)
except Exception,e:
    print e
else:    
    filelist = [] #to store all files
    ftp.retrlines('LIST',filelist.append)    # append to list  
    f=0
    for f in filelist:
        if "public_html" in f:
            #do something
            f=1
    if f==0:
        print "No public_html"
        #do your processing here
24

Nslt会列出FTP服务器上所有文件的一个列表。你只需要检查一下你的文件夹名称是否在里面就可以了。

from ftplib import FTP 
ftp = FTP('yourserver')
ftp.login('username', 'password')

folderName = 'yourFolderName'
if folderName in ftp.nlst():
    #do needed task 

撰写回答