【问题标题】:Delete all files and folders after connecting to FTP连接 FTP 后删除所有文件和文件夹
【发布时间】:2012-04-06 11:30:52
【问题描述】:

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

有人知道为什么吗?

【问题讨论】:

    标签: python ftp ftplib


    【解决方案1】:
    for something in ftp.nlst():
        try:
            ftp.delete(something)
        except Exception:
            ftp.rmd(something)
    

    还有其他方法吗?

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:
        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)
        

        【讨论】:

        • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
        【解决方案4】:
        ftp.nlst()
        

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

        os.remove()
        

        以上语句需要文件路径

        【讨论】:

        • 是的,我正在迭代列表并尝试删除文件,我认为这里不需要路径
        • 但是 os.remove() 不是在本地删除而不是远程对应于 ftp.nlst() 返回的内容吗?我错过了什么?
        • docs.python.org/library/os.html 表示 os.remove() 的参数是路径,而不仅仅是文件名。
        • @octopusgrabbus 你是对的。我认为可以使用 ftp.retrlines('MSDL') 检查文件/目录,然后相应地形成 ftp 路径。还有其他方法吗?
        • 它在 Python 的 ftp 的 ftp 文档中,我没有我的示例。
        【解决方案5】:
        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()
        #--------------------------------------------------
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多