Skip to content

Instantly share code, notes, and snippets.

@artlogic
Created May 8, 2012 04:44
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save artlogic/2632647 to your computer and use it in GitHub Desktop.
Save artlogic/2632647 to your computer and use it in GitHub Desktop.
Python ftplib rmtree
def FtpRmTree(ftp, path):
"""Recursively delete a directory tree on a remote server."""
wd = ftp.pwd()
try:
names = ftp.nlst(path)
except ftplib.all_errors as e:
# some FTP servers complain when you try and list non-existent paths
_log.debug('FtpRmTree: Could not remove {0}: {1}'.format(path, e))
return
for name in names:
if os.path.split(name)[1] in ('.', '..'): continue
_log.debug('FtpRmTree: Checking {0}'.format(name))
try:
ftp.cwd(name) # if we can cwd to it, it's a folder
ftp.cwd(wd) # don't try a nuke a folder we're in
FtpRmTree(ftp, name)
except ftplib.all_errors:
ftp.delete(name)
try:
ftp.rmd(path)
except ftplib.all_errors as e:
_log.debug('FtpRmTree: Could not remove {0}: {1}'.format(path, e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment