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

时间:2012-04-06 11:30:52

标签: 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)

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

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

任何人都知道为什么?

4 个答案:

答案 0 :(得分:7)

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

还有其他方法吗?

答案 1 :(得分:1)

此函数递归删除任何给定的路径:

# 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')

答案 2 :(得分:0)

ftp.nlst()

上述语句返回文件名列表

os.remove()

上述声明需要文件路径

答案 3 :(得分: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()
#--------------------------------------------------