在python中从回收站还原文件

在python中从回收站还原文件,python,recycle-bin,Python,Recycle Bin,在python中是否有从回收站恢复文件的方法 代码如下: from send2trash import send2trash file_name = "test.txt" operation = input("Enter the operation to perform[delete/restore]: ") if operation == "delete": send2trash(file_name) print

在python中是否有从回收站恢复文件的方法

代码如下:

from send2trash import send2trash

file_name = "test.txt"

operation = input("Enter the operation to perform[delete/restore]: ")

if operation == "delete":
    send2trash(file_name)
    print(f"Successfully deleted {file_name}")

else:
    # Code to restore the file from recycle bin.
    pass
在这里,当我在
input()
函数中键入
“restore”
时,我想从回收站还原已删除的文件

有没有办法用python实现这一点

如果有人能帮我,那就太好了

编辑:

谢谢你的回答@Kenivia,但我面临一个小问题:

import winshell

r = list(winshell.recycle_bin())  # this lists the original path of all the all items in the recycling bin
file_name = "C:\\test\\Untitled_1.txt" # This file is located in the recycle bin

index = r.index(file_name) # to determine the index of your file

winshell.undelete(r[index].original_filename())

运行此代码时,我得到一个错误:
ValueError:'C:\\test\\Untitled_1.txt'不在列表中
。你能帮我一下吗?

这取决于你的操作系统

Linux

只需将其从垃圾箱文件夹移动到原始路径即可。垃圾箱文件夹的位置因发行版而异,但这是它通常所在的位置

有一种方法,你可以使用,或通过挖掘代码获得一些想法

import subprocess as sp # here subprocess is just used to run the command, you can also use os.system but that is discouraged

sp.run(['mv','/home/USERNAME/.local/share/Trash/files/test.txt', '/ORIGINAL/PATH/')
macOS

在macOS上,除了垃圾路径是
~/.trash

import subprocess as sp

sp.run(['mv','~/.Trash/test.txt', '/ORIGINAL/PATH/')
请注意,macOS将有关文件的信息存储在
~/.Trash/.DS_Store
中,Linux将文件存储在
/home/USERNAME/.local/share/Trash/info/
中。如果您不知道文件的原始路径,这将非常有用

窗口

您必须使用
winshell
。有关更多详细信息,请参阅

import winshell 

r = list(winshell.recycle_bin())  # this lists the original path of all the all items in the recycling bin
index = r.index("C:\ORIGINAL\PATH\test.txt") # to determine the index of your file

winshell.undelete(r[index].original_filename())

您好,谢谢您的回答,但是当我使用
r.index(file)
时,python给了我一个错误
ValueError:“file”不在列表中,尽管我给出的文件路径是正确的。有什么办法可以解决这个问题吗?您可能使用了
r.index(“文件”)
而不是
r.index(文件)
,如果没有,请打印列表
r
并查找文本文件的路径。我试着打印列表,列表中的文件路径似乎与我给出的路径相同。错误消息提到
'file'
这一事实意味着您将字符串-
“file”
而不是名为
file
的变量。你能不能仔细检查一下你是否将正确的内容传递到了
r.index()
?你能通过编辑问题或在评论中发送问题来显示你的全部代码吗?