python 将文件移入回收站

发布时间 2023-12-28 15:48:59作者: 记录——去繁就简

 

python如果要删除一个文件,通常使用

os.remove(filename)

但是这样就直接从磁盘删除了。

有些文件需要删除到回收站,以便误删后还能找回文件

from win32com.shell import shell,shellcon
debug=False
def deltorecyclebin(filename):
    print('deltorecyclebin', filename)
    # os.remove(filename) #直接删除文件,不经过回收站
    if not debug:
        res= shell.SHFileOperation((0,shellcon.FO_DELETE,filename,None, shellcon.FOF_SILENT | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION,None,None))  #删除文件到回收站
        if not res[1]:
            os.system('del '+filename)

安装模块

pip install pywin32

假如安装后报错,显示import win32file ImportError: DLL load failed

【解决方案】

从定位上看是pywin32这个库出现了问题,用conda list查看pywin32 显示的版本是223

他说要把pywin32降级到224。

pip install pywin32==224
在安装过程中发现,在我的环境中pywin32实际上是227,不是conda list中显示的223。

安装224版本之后,问题解决。
参考了这个博主的解决办法https://www.cnblogs.com/longweiqiang/p/13086491.html