When using python os.rmdir, get PermissionError: [WinError 5] Access is denied

When using python os.rmdir, get PermissionError: [WinError 5] Access is denied

我正在构建一个文件传输脚本,源清理功能使用了 os.rmdir('C:\Users\Grav\Desktop\TestDir0\Om')。这是我得到的错误:

PermissionError: [WinError 5] Access is denied: 'C:\Users\Grav\Desktop\TestDir0\Om'

我通过 Windows 7 检查了文件夹 Om 的权限,它们设置为允许删除我的用户帐户。我还尝试将我的解释器设置为 运行 作为管理员。问题仍然存在,我受阻了。非常感谢任何有见识的人!

你能检查是否:

  1. 您不在目录 0m 和 运行 脚本中。
  2. 您没有任何 windows 打开该列表 0m 目录。
  3. 由于 0mTestDir0 的子目录,您拥有 TestDir0
  4. 的正确权限

我在这里找到了解决方案:What user do python scripts run as in windows?

似乎有问题的文件夹具有顽固的只读属性。添加一个处理程序来更改此类只读标志对我来说就像一个魅力。

各位发帖的,帮我找到了最终答案,谢谢!

我有同样的问题,可以通过 shutil 模块解决。

import shutil
shutil.rmtree('/path/to/your/dir/')

在 file/folder 的属性中取消选中只读属性框。

删除目录前尝试删除目录中的所有文件:

import os
path_to_dir  = 'C:\Users\Desktop\temp'  # path to directory you wish to remove
files_in_dir = os.listdir(path_to_dir)     # get list of files in the directory

for file in files_in_dir:                  # loop to delete each file in folder
    os.remove(f'{path_to_dir}/{file}')     # delete file

os.rmdir(path_to_dir)                      # delete folder