Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all files and folders after connecting to FTP

Tags:

python

ftp

ftplib

I want to connect through FTP to an address and then delete all contents. Currently I am using this code:

from ftplib import FTP
import shutil
import os

ftp = FTP('xxx.xxx.xxx.xxx')
ftp.login("admin", "admin")

for ftpfile in ftp.nlst():
    if os.path.isdir(ftpfile)== True:
        shutil.rmtree(ftpfile)
    else:
        os.remove(ftpfile)

My problem is I always get this error when he is trying to delete the first file:

    os.remove(ftpfile)
WindowsError: [Error 2] The system cannot find the file specified: somefile.sys

Anyone has an idea why?

like image 265
Adrian Avatar asked Dec 13 '22 03:12

Adrian


2 Answers

for something in ftp.nlst():
    try:
        ftp.delete(something)
    except Exception:
        ftp.rmd(something)

Any other ways?

like image 141
pravin Avatar answered Dec 14 '22 18:12

pravin


This function deletes any given path recursively:

# python 3.6    
from ftplib import FTP

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)

ftp = FTP(HOST, USER, PASS)
remove_ftp_dir(ftp, 'path_to_remove')
like image 44
Dmytro Gierman Avatar answered Dec 14 '22 17:12

Dmytro Gierman