连接到FTP后删除所有文件和文件夹

Adr*_*ian 4 python

我想通过FTP连接到一个地址,然后删除所有内容.目前我正在使用此代码:

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)
Run Code Online (Sandbox Code Playgroud)

我的问题是他在尝试删除第一个文件时总是遇到此错误:

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

任何人都知道为什么?

小智 7

 for something in ftp.nlst():
     try:
             ftp.delete(something)
     except Exception:
             ftp.rmd(something)
Run Code Online (Sandbox Code Playgroud)

还有其他方法吗?


Acc*_*man 5

此函数以递归方式删除任何给定路径:

# 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')
Run Code Online (Sandbox Code Playgroud)