Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何轻松删除只读文件?_Python_Windows - Fatal编程技术网

Python 如何轻松删除只读文件?

Python 如何轻松删除只读文件?,python,windows,Python,Windows,我想让我的代码删除临时文件夹和预回迁文件夹的所有内容,但是有些文件是只读的,因此代码返回错误5:拒绝访问 def deletetemp(): 尝试: 对于root2,dirs,os.walk(r'C:\Windows\Temp')中的文件: 对于文件中的f: 取消链接(os.path.join(root2,f)) 对于目录中的d: rmtree(os.path.join(root2,d)) 对于root2,dirs,os.walk(r'C:\Windows\Prefetch')中的文件: 对于文

我想让我的代码删除临时文件夹和预回迁文件夹的所有内容,但是有些文件是只读的,因此代码返回错误5:拒绝访问

def deletetemp():
尝试:
对于root2,dirs,os.walk(r'C:\Windows\Temp')中的文件:
对于文件中的f:
取消链接(os.path.join(root2,f))
对于目录中的d:
rmtree(os.path.join(root2,d))
对于root2,dirs,os.walk(r'C:\Windows\Prefetch')中的文件:
对于文件中的f:
取消链接(os.path.join(root2,f))
对于目录中的d:
rmtree(os.path.join(root2,d))
对于root2,dirs,os.walk(r'C:\Users\*myusername*\AppData\Local\Temp')中的文件:
对于文件中的f:
取消链接(os.path.join(root2,f))
对于目录中的d:
rmtree(os.path.join(root2,d))
x、 配置(text=“已删除临时/预回迁文件!”)
例外情况除外,如e:
x、 配置(text=str(e))
Tkinter回调中出现异常 回溯(最近一次呼叫最后一次): 文件“C:/Users/*myusername*/.PyCharmCE2019.1/config/scratches/scratch.py”,第10行,在deletetemp中 取消链接(os.path.join(root2,f)) PermissionError:[WinError 5]访问被拒绝:“C:\\Windows\\Temp\\vcredist\u x86.exe”

如果你还没注意到的话,我是个编码高手。请尝试提供简单的答案(当然,不要完全为我编写代码)。而且,我确实在寻找答案,但没有找到答案。如果有一个地方,请重定向我!我将查看它并尝试从中提取一些内容。

如前所述,尝试使用更改文件的权限
os.chmod(path\uu,stat.S\u IWRITE)
并将其删除

您看到了吗:?谢谢!我设法做到了。然而,我实际上是从Denis Rasulev(他对我的问题发表了评论)的评论中得到了代码,我发现了一个代码snipplet,使它工作起来。我现在有一个不同的问题,但是这个问题被解决了!当然,readonly是一个文件属性,而不是权限。Python从MSVC复制了这种奇怪的行为,这种行为可以追溯到20世纪80年代的C for MS-DOS。如果我们在Linux文件系统中有一个[i]mmutable文件,我们就不能通过
chmod
使其可写。是的,完全缺乏一致性。