每次我尝试在 Python 3.5.1 中使用 os.remove() 删除文件时,我都会收到此消息 PermissionError: [WinError 5] Access is denied
这是简单的代码:
def clean_thrash(path):
dirlist=get_dirlist(path)
for f in dirlist:
fullname=os.path.join(path,f)
if fullname == os.path.join(path,"thrash.txt"):
os.remove(path)
if os.path.isdir(fullname):
clean_thrash(fullname)
甚至没有删除目录或子目录中的单个文件。
请您参考如下方法:
我也遇到了这个问题,经过搜索找到了很好的解决方案。
本质上,在调用 os.remove(file_name) 之前,我们需要更改文件权限。
导入统计数据- 在调用
os.remove之前,调用os.chmod(file_name, stat.S_IWRITE)
例如:
import os
import stat
def clean_thrash(path):
dirlist=get_dirlist(path)
for f in dirlist:
fullname=os.path.join(path,f)
if fullname == os.path.join(path,"thrash.txt"):
os.chmod(fullname , stat.S_IWRITE)
os.remove(fullname)
if os.path.isdir(fullname):
clean_thrash(fullname)
我希望这能解决您的问题。
