python代码实现Mac,windows,linux删除文件到垃圾桶(不使用os.remove())

代码

调用move2Trash(deletePath)即可
例如:
move2Trash("./111.txt")
linux系统需要安装软件:sudo apt-get install trash-cli

#!/usr/bin/env python
import os
import platform

def move2Trash(deletePath):
    # windows
    if (platform.system() == 'Windows'):
        from win32com.shell import shell,shellcon
        if os.path.exists(deletePath):
            shell.SHFileOperation((0, shellcon.FO_DELETE, deletePath, None,
                                   shellcon.FOF_SILENT | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION,
                                   None, None))
        else:
            print(deletePath + " not exists!")
    # linux
    elif (platform.system() == 'Linux'):
        # 需要安装依赖软件:sudo apt-get install trash-cli
        if os.path.exists(deletePath):
            cmd = 'trash ' + deletePath
            os.system(cmd)
        else:
            print(deletePath + " not exists!")
    # macOS
    elif (platform.system() == 'Darwin'):
        import subprocess
        if os.path.exists(deletePath):
            absPath = os.path.abspath(deletePath).replace('\\', '\\\\').replace('"', '\\"')
            cmd = ['osascript', '-e',
                   'tell app "Finder" to move {the POSIX file "' + absPath + '"} to trash']
            print(cmd)
            subprocess.call(cmd, stdout=open(os.devnull, 'w'))
        else:
            print(deletePath + " not exists!")


已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:上身试试 返回首页