代码
调用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!")