2

I'm trying to delete a folder using ftplib with Python. I've tried ftp.delete, but it only accepts files I've tried ftp.rmd but that only works with empty folders. Tried a recursion function I found online:

def remove_ftp_dir(ftp, path):
    for (name, properties) in ftp.mlsd(path=path): 
        if name in ['.',   '..']:
            continue
        elif properties['type'] == 'file':
            ftp.delete(f"{path}/{name}")
        elif properties['type'] == 'dir':
            remove_ftp_dir(ftp, f"{path}/{name}")
    ftp.rmd(path) 

When trying to iterate over the ftp.mlsd I get:

ftplib.error_perm: 500 Invalid command: "MLSD"

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Ben Pinhas
  • 63
  • 6

1 Answers1

1

for everyone needing this in the future, ive written a delete function the works on evry server:

def delete_dir (ftp , deleteDirPath):
ftp.cwd(deleteDirPath)
print("Current wd --- " , ftp.pwd())
contents =ftp.nlst(deleteDirPath)
# if empty dir - delete it
try:
    ftp.rmd(deleteDirPath)
except error_perm as e:
    if not e.args[0].startswith("550"):
        raise

# loop on all folder objects list
for name in contents:
    try:
        # delete if file
        print(deleteDirPath + "/" + name)
        ftp.delete( deleteDirPath + "/" + name)
        #time.sleep(0.7)
        print("Succeed delete = ", deleteDirPath + "/" + name)
    except:
        # if folder
        delete_dir(ftp ,deleteDirPath + "/" + name)
        
# if empty dir - delete it
try:
    ftp.rmd(deleteDirPath)
except error_perm as e:
    if not e.args[0].startswith("550"):
        raise
Ben Pinhas
  • 63
  • 6
  • You have the indentation wrong + You have the block with `rmd` unnecessary twice in your code. The second instance is enough. + You never check the result of `cwd`. If you encounter a file that you do not have permissions to delete, you code will start doing lot of crazy stuff. + Hard coding `550` code will definitely not make your code *"work on evry server"*. – Martin Prikryl Jul 04 '21 at 06:39