Delete all files and folders after connecting to FTP

I want to connect via FTP to an address and then delete all content. I am currently 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: I always get this error when it tries to delete the first file:

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

      

Anyone have an idea why?

+3


source to share


3 answers


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

      



Any other ways?

+5


source


ftp.nlst()

      

The above statement returns a list of filenames .



os.remove()

      

The above description requires a file path .

0


source


from ftplib import FTP
#--------------------------------------------------
class FTPCommunicator():

    def __init__(self):

        self.ftp = FTP()
        self.ftp.connect('server', port=21, timeout=30)
        self.ftp.login(user="user", passwd="password")

    def getDirListing(self, dirName):

        listing = self.ftp.nlst(dirName)

        # If listed a file, return.
        if len(listing) == 1 and listing[0] == dirName:
            return []

        subListing = []
        for entry in listing:
            subListing += self.getDirListing(entry)

        listing += subListing

        return listing

    def removeDir(self, dirName):

        listing = self.getDirListing(dirName)

        # Longest path first for deletion of sub directories first.
        listing.sort(key=lambda k: len(k), reverse=True)

        # Delete files first.
        for entry in listing:
            try:
                self.ftp.delete(entry)
            except:
                pass

        # Delete empty directories.
        for entry in listing:
            try:
                self.ftp.rmd(entry)
            except:
                pass

        self.ftp.rmd(dirName)

    def quit(self):

        self.ftp.quit()
#--------------------------------------------------
def main():

    ftp = FTPCommunicator()
    ftp.removeDir("/Untitled")
    ftp.quit()
#--------------------------------------------------
if __name__ == "__main__":
    main()
#--------------------------------------------------

      

0


source







All Articles