python刪除文件夾下的所有內容


python嘗試清空文件夾下內容,遇到刪除不掉的文件或文件夾,會跳過。

import os
from typing import Union
import stat

def clean_folder(folder_path: Union[str, list[str]]):
    """Remove all files and folders within the folder_path.

    :param folder_path:
    :return:
    """
    if isinstance(folder_path, str):
        folder_path = [folder_path]

    for folder in folder_path:
        for root, dirs, files in os.walk(folder, topdown=False):
            for name in files:
                file_name = os.path.join(root, name)
                try:
                    os.unlink(file_name)
                except PermissionError:
                    # 某些只讀文件刪不掉,需要先賦予 寫 的權限,然后再刪除
                    os.chmod(file_name, stat.S_IWRITE)
                    try:
                        os.unlink(file_name)
                    except Exception:
                        pass
            for name in dirs:
                # 某些文件夾也刪除不掉,譬如U盤的系統文件夾(保存U盤自身信息的文件夾)
                try:
                    os.rmdir(os.path.join(root, name))
                except Exception:
                    pass


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM