この関数のドキュメントを読みましたが、正しく理解できていないと思います。誰かが私が欠けているものを教えてくれるなら、または私が正しいなら、それは大きな助けになるでしょう。これが私の理解です:
この関数を使用するshutil.rmtree(path)と、パス全体ではなく、指定されたディレクトリのみが削除されます。IE:
shutil.rmtree('user/tester/noob')
これを使用すると、「noob」ディレクトリのみが削除されますか?完全なパスではありませんか?
この関数のドキュメントを読みましたが、正しく理解できていないと思います。誰かが私が欠けているものを教えてくれるなら、または私が正しいなら、それは大きな助けになるでしょう。これが私の理解です:
この関数を使用するshutil.rmtree(path)と、パス全体ではなく、指定されたディレクトリのみが削除されます。IE:
shutil.rmtree('user/tester/noob')
これを使用すると、「noob」ディレクトリのみが削除されますか?完全なパスではありませんか?
noobがディレクトリの場合、shutil.rmtree()関数はnoobその下のすべてのファイルとサブディレクトリを削除します。つまり、noob削除するツリーのルートです。
これにより、指定したパスの最後のディレクトリのみが確実に削除されます。試してみてください:
mkdir -p foo/bar
python
import shutil
shutil.rmtree('foo/bar')
...削除するだけ'bar'です。
ここにはいくつかの誤解があります。
このような木を想像してみてください。
- user
- tester
- noob
- developer
- guru
削除したい場合は、を実行userしてくださいshutil.rmtree('user')。これも削除user/testerさuser/tester/noobれ、内部にあるためuserです。ただし、とも中にあるため、削除されuser/developerます。user/developer/guruuser
rmtree('user/tester/noob')削除するuserとしたら、なくなったらtesterどういう意味ですか?user/developeruser
または、 http://docs.python.org/2/library/os.html#os.removedirsのようなものを意味しますか?
ディレクトリが空ではないために失敗するまで、削除された各ディレクトリの親を削除しようとします。したがって、私の例のツリーでos.removedirs('user/tester/noob')は、最初に削除noobし、次に削除しようとしtesterます。これは空なので問題ありませんが、削除したくないがuser含まれているため、停止してそのままにしておきます。developer
**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.