4

我想通过 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)

我的问题是,当他尝试删除第一个文件时,我总是会收到此错误:

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

任何人都知道为什么?

4

5 回答 5

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

还有其他方法吗?

于 2012-04-06T14:17:46.343 回答
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')
于 2019-01-07T10:29:39.063 回答
2
from ftplib import FTP
import shutil
import os

ftp = FTP("hostname")

ftp.login("username", "password")


def deletedir(dirname):

    ftp.cwd(dirname)

    print(dirname)

    for file in ftp.nlst():

        try:
            ftp.delete(file)

        except Exception:
            deletedir(file)

    ftp.cwd("..")
    ftp.rmd(dirname)
            

for ftpfile in ftp.nlst():

    try:

        ftp.delete(ftpfile)

    except Exception:

        deletedir(ftpfile)
于 2021-10-16T18:07:11.550 回答
0
ftp.nlst()

上面的语句返回一个文件名列表

os.remove()

上面的语句需要一个文件路径

于 2012-04-06T11:58:55.413 回答
0
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()
#--------------------------------------------------
于 2017-11-07T18:46:03.050 回答