每次我尝试删除os.remove()
Python 3.5.1 中使用的文件时,都会收到此消息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)
Run Code Online (Sandbox Code Playgroud)
甚至没有删除目录或子目录中的单个文件。
小智 11
如果您使用的是 Windows,您可以简单地执行以下操作:
import shutil
shutil.rmtree(directory_path)
Run Code Online (Sandbox Code Playgroud)
希望这有效!
小智 5
我也遇到了这个问题,经过搜索找到了一个很好的解决方案。
本质上,在调用之前os.remove(file_name)
我们需要更改文件权限。
import stat
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)
Run Code Online (Sandbox Code Playgroud)
我希望这可以解决您的问题。
归档时间: |
|
查看次数: |
24744 次 |
最近记录: |