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

2024-05-15 01:45:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用此脚本连接到示例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)是否存在,目录是否存在cd,然后执行其他代码并退出;如果不立即执行代码并退出?


Tags: 代码fromimport服务器目录脚本示例nl
3条回答

Nslt将列出ftp服务器中所有文件的数组。检查一下你的文件夹名是否在那里。

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

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

您可以通过控制连接发送“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

当然,上面的代码不是100%可靠的,需要一个真正的解析器。 您可以在ftplib.py中查看MLSD命令的实现,它非常类似(MLSD与MLST的不同之处在于,通过数据连接发送的响应是相同的,但发送的行的格式是相同的): http://hg.python.org/cpython/file/8af2dc11464f/Lib/ftplib.py#l577

你可以使用一个列表。示例

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

相关问题 更多 >

    热门问题