簡體   English   中英

如何使用 rmtree() 刪除文件夾和文件

[英]How to use the rmtree() to delete folders and files

我正在嘗試刪除此路徑中的文件夾和文件:'Users/ryanunderwood/Desktop'

這是我的代碼:

import shutil
shutil.rmtree('Users/ryanunderwood/Desktop')

但是,拋出此錯誤:

Traceback (most recent call last):
  File "/Users/ryanunderwood/Documents/Python files/wipeComputer.py", line 10, in <module>
    shutil.rmtree('Users/ryanunderwood/Desktop')
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 516, in rmtree
    return _rmtree_unsafe(path, onerror)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 377, in _rmtree_unsafe
    onerror(os.scandir, path, sys.exc_info())
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 374, in _rmtree_unsafe
    with os.scandir(path) as scandir_it:
FileNotFoundError: [Errno 2] No such file or directory: 'Users/ryanunderwood/Desktop'

我該如何解決?

您沒有正確指定桌面目錄的整個路徑。 可能類似於shutil.rmtree("C:/Users/ryanunderwood/Desktop") ,具體取決於桌面文件夾所在的驅動器/分區。

有兩種路徑:本地路徑和絕對路徑。

本地路徑(就像您當前使用的那樣)是文件夾列表,將被解釋為從當前工作文件夾開始。 因此,結果將取決於您在哪里/如何運行您的程序(工作字典)。 如果您運行 python 的文件夾包含文件夾“Foo”, shutil.rmtree('Foo')實際上可以工作。

但是,這可能不是您想要的。 如果您始終希望以同一文件夾為目標,請使用絕對路徑,該路徑以驅動器規格(在本例中為'C:' )開頭,並包含整個嵌套文件夾列表,直到您到達目標為止。 在本例中為"C:/Users/ryanunderwood/Desktop" ,假設您具有 Windows 的標准文件夾結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM