簡體   English   中英

刪除目錄中的文件/刪除不為空的某些目錄

[英]Deleting files in directory / deleting certain directory that is not empty

我正在創建一個登錄系統,我想在系統重新啟動時重置該信息。 我已將信息存儲在名為accounts的目錄中的文本文件中。 data/accounts目錄中有文本文件和子目錄。

我以為可以使用os.remove ,但是它不起作用。 到目前為止,我已經嘗試過了。

import os

def infoReset():
    os.remove("data/accounts/")

但這只是給我帶來了"operation not permitted"錯誤。 如何刪除data/accounts目錄及其內容?

考慮使用TemporaryDirectory ,完成后會自動將其刪除。 這樣可以避免與手動和潛在的不安全目錄管理有關的錯誤。

根據文檔

在上下文完成或臨時目錄對象被破壞后,新創建的臨時目錄及其所有內容將從文件系統中刪除。

可以從返回對象的名稱屬性中檢索目錄名稱。 當返回的對象用作上下文管理器時,該名稱將分配給with語句中as子句的目標(如果有)。

可以通過調用cleanup()方法顯式清除目錄。

這是一個適用於您的用例的精簡示例:

import tempfile

# At the beginning of your program, create a temporary directory.
tempdir = tempfile.TemporaryDirectory()

...

# Later, remove the directory and its contents.
tempdir.cleanup()

或者,根據項目中該方法的可行性,使用上下文管理器。

import tempfile

with tempfile.TemporaryDirectory() as tmpdirname:
    # Write files in the directory...
    # ...

    # As soon as your exit this block, the directory is automatically cleaned up.

os.remove()用於文件,而不用於目錄。 os.rmdir()用於刪除目錄,但僅用於空目錄。 要刪除目錄及其內容,請使用shutil.rmtree()

import shutil

def infoReset():
    shutil.rmtree("data/accounts/")

暫無
暫無

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

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