简体   繁体   中英

Python ftplib Delete Folder and Files Script (with hidden files)

I have prepared a simple python script to delete all directories and files (with hidden files) and sharing you. You can use it or develop it.

Main function:

# FTP
with FTP(hostname) as ftp:
    ftp.login(username, password)
    
    # delete all files
    delete(ftp, "public_html")
    ftp.cwd("public_html")

Required functions:

_ftp = None

def isFile(path):
    curDir = _ftp.pwd()
    try:
        _ftp.cwd(path)  # if we can cwd to it, it's a folder
        _ftp.cwd(curDir) # return current folder
        return False
    except ftplib.all_errors:
        return True

def isDirectory(path):
    curDir = _ftp.pwd()
    try:
        _ftp.cwd(path)  # if we can cwd to it, it's a folder
        _ftp.cwd(curDir) # return current folder
        return True
    except ftplib.all_errors:
        return False

def delete(ftp, path):
    global _ftp
    _ftp = ftp

    _ftp.cwd(path)
    files = _ftp.mlsd()

    for file, facts in files:  
        if file == "." or file == ".." or file == ".well-known": continue

        # if file, directly delete it
        if isFile(file):
            print("FILE deleting: " + file)
            _ftp.delete(file)
        
        if isDirectory(file):
            print("FOLDER deleting: " + file)
            try:
                _ftp.rmd(file)                
            except ftplib.all_errors:
                delete(_ftp, file)
                _ftp.rmd(file)
            
    _ftp.cwd("../")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM