用Python从回收站恢复文件

4

有办法在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' is not in list。请问您能否帮我解决这个问题?
2个回答

4

这取决于您的操作系统。

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 上,你需要做和 Linux 一样的事情,只不过垃圾箱的路径是 ~/.Trash

import subprocess as sp

sp.run(['mv','~/.Trash/test.txt', '/ORIGINAL/PATH/')

请注意,macOS将有关文件的信息存储在~/.Trash/.DS_Store,而Linux将它们存储在/home/USERNAME/.local/share/Trash/info/。 如果您不知道文件的原始路径,则这可能非常有用。
在Windows下,您需要使用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' is not in list,尽管我给出的文件路径是正确的。有没有什么方法可以解决这个问题? - Lenovo 360
请问您能否展示您的整个代码,可以通过编辑问题或在评论中发送。 - Kenivia
我使用了类似于 index = r.index(x) 的语句,其中 x 是一个变量,存储了文件的路径。 - Lenovo 360
让我们在聊天中继续这个讨论 - Kenivia
1
@Kevinia:嘿,我知道我来晚了,但我想我已经找到问题所在了(Windows)。r.index(file)不起作用的原因是r中的每个项目都是ShellRecycledItem()的实例,而file只是一个字符串。ShellRecycledItem()类有一个名为original_filename()的方法,我们可以使用它来获取文件的实际名称。因此,我们可以像这样做r = [name.original_filename() for name in list(winshell.recycle_bin())],而不是r = list(winshell.recycle_bin()),以使r.index(file)起作用。非常感谢您的帮助!点赞+采纳。 - Lenovo 360
显示剩余3条评论

0

Google Colab(您是root用户)

导入Python的shell实用程序:

import shutil

将文件从回收站移动到所选目标:
shutil.move('/root/.local/share/Trash/files/<deleted-file>', '<destination-path>')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接