如何在Windows上使用Python删除C:/Users/testuser下的所有文件和文件夹

lndjwyie  于 2023-10-22  发布在  Windows
关注(0)|答案(3)|浏览(160)

我需要一个Python脚本来删除Windows上C:/Users文件夹下的完整用户文件夹。我尝试了下面的代码,但我得到的几个文件的错误:

[WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/test\\AppData\\Local\\Microsoft\\Windows\\UsrClass.dat'

注意:在Windows上,我以用户A作为管理员登录,并试图删除用户B文件夹。在删除用户文件夹之前,我正在使用此命令删除注册表项:reg.exe", "delete", f"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{profile}
下面是我尝试的Pyhton代码:

import os
import shutil
profile_folder_path = "C:/Users/test"
for base_dir, dirs, files in os.walk(profile_folder_path):
    for file in files:
        try:
            print(os.path.join(base_dir, file))
            os.chmod(os.path.join(base_dir, file), 0o777)
            os.remove(os.path.join(base_dir, file))
        except Exception as ex:
            print(f"Can not delete file: {ex}")
    for folder in dirs:
        try:
            print(os.path.join(base_dir, folder))
            os.chmod(os.path.join(base_dir, folder), 0o777)
            # os.rmdir(os.path.join(base_dir, folder))
            shutil.rmtree(os.path.join(base_dir, folder))

        except Exception as ex:
            print(f"Can not delete folder: {ex}")

我希望删除完整的用户文件夹:C:/Users/testuser我的目标是删除Windows上未使用的用户及其用户数据文件夹。

z31licg0

z31licg01#

我对你的代码做了一些修改,它在我的笔记本电脑上工作。

import os
import shutil
import subprocess

def terminate_processes(username):
    try:
        subprocess.run(["taskkill", "/F", "/IM", f"{username}.exe"], check=True, capture_output=True)
    except subprocess.CalledProcessError as e:
        print(f"Error terminating processes: {e.stdout.decode()}")

def delete_user_profile(user_folder_path):
    try:
        shutil.rmtree(user_folder_path)
        print(f"Deleted profile folder: {user_folder_path}")
    except Exception as ex:
        print(f"Failed to delete profile folder: {ex}")

if __name__ == "__main__":
    target_username = "test"  
    profile_folder_path = os.path.join("C:/Users", target_username)
    terminate_processes(target_username)
    delete_user_profile(profile_folder_path)
vdzxcuhz

vdzxcuhz2#

一旦你确定相关目录中的文件都没有被使用,那么只需递归删除该目录:

from shutil import rmtree
from pathlib import Path

DIR = '/Users/FOO'

if (directory := Path(DIR)).is_dir():
    try:
        rmtree(directory)
    except Exception as e:
        print(e)
else:
    print(f'{DIR} is not a directory')
gupuwyp2

gupuwyp23#

我找到了一个Powershell命令来实现这一点:

Get-CimInstance -ClassName Win32_UserProfile | Where {$_.LocalPath -eq 'C:\Users\test'} | Remove-CimInstance -Verbose -Confirm:$false

相关问题