【问题标题】:shutil.rmtree() clarificationshutil.rmtree() 说明
【发布时间】:2012-06-03 19:40:43
【问题描述】:

我已经阅读了这个函数的文档,但是,我认为我没有正确理解它。如果有人能告诉我我错过了什么,或者我是正确的,那将是一个很大的帮助。这是我的理解:

使用shutil.rmtree(path) 函数,它只会删除指定的目录,而不是整个路径。即:

shutil.rmtree('user/tester/noob')

使用这个,它只会删除'noob'目录对吗?不是完整的路径?

【问题讨论】:

  • “不是完整路径”是什么意思?如果它“删除完整路径”会发生什么?
  • 'user/tester/noob' 中的完整路径。 IE删除包含tester和noob的用户目录。
  • @IT Ninja:你测试的结果是什么? -步骤 1
  • 它的工作方式与rm -rf /dir1/dir2/dir3 完全一样,它只会删除 dir3 及其下的所有内容

标签: python python-2.7 shutil


【解决方案1】:

如果 noob 是一个目录,shutil.rmtree() 函数将删除noob 以及它下面的所有文件和子目录。也就是说,noob 是要移除的树的根。

【讨论】:

    【解决方案2】:

    这肯定只会删除指定路径中的最后一个目录。 试试看吧:

    mkdir -p foo/bar
    python
    import shutil
    shutil.rmtree('foo/bar')
    

    ...只会删除'bar'

    【讨论】:

      【解决方案3】:

      这里有些误会。

      想象一棵这样的树:

       - user
         - tester
           - noob
         - developer
           - guru
      

      如果您想删除user,只需执行shutil.rmtree('user')。这也将删除user/testeruser/tester/noob,因为它们在user 中。但是,它也会删除user/developeruser/developer/guru,因为它们也在user 中。

      如果rmtree('user/tester/noob') 会删除usertester,那如果user 消失了,你的意思是user/developer 会存在吗?


      或者你的意思是像http://docs.python.org/2/library/os.html#os.removedirs这样的东西?

      它会尝试删除每个已删除目录的父目录,直到由于目录不为空而失败。所以在我的示例树中,os.removedirs('user/tester/noob') 将首先删除noob,然后它会尝试删除tester,这没关系,因为它是空的,但它会停在user 并不管它,因为它包含@ 987654340@,我们不想删除。

      【讨论】:

        【解决方案4】:
        **For Force deletion using rmtree command in Python:**
        
        [user@severname DFI]$ python
        Python 2.7.13 (default, Aug  4 2017, 17:56:03)
        [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux2
        Type "help", "copyright", "credits" or "license" for more information.
        >>> import shutil
        >>> shutil.rmtree('user/tester/noob')
        
        
        
        But what if the file is not existing, it will throw below error:
        
        
        >>> shutil.rmtree('user/tester/noob')
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
          File "/usr/local/lib/python2.7/shutil.py", line 239, in rmtree
            onerror(os.listdir, path, sys.exc_info())
          File "/usr/local/lib/python2.7/shutil.py", line 237, in rmtree
            names = os.listdir(path)
        OSError: [Errno 2] No such file or directory: 'user/tester/noob'
        >>>
        
        **To fix this, use "ignore_errors=True" as below, this will delete the folder at the given if found or do nothing if not found**
        
        
        >>> shutil.rmtree('user/tester/noob', ignore_errors=True)
        >>>
        
        Hope this helps people who are looking for force  folder deletion using rmtree.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-01-01
          • 2011-01-04
          • 2015-04-03
          • 2013-10-19
          • 2013-08-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多