有办法在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
。请问您能否帮我解决这个问题?
r.index(file)
时,Python 给出了一个错误ValueError: 'file' is not in list
,尽管我给出的文件路径是正确的。有没有什么方法可以解决这个问题? - Lenovo 360index = r.index(x)
的语句,其中 x 是一个变量,存储了文件的路径。 - Lenovo 360r.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