如何解决在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
这里当我在 "restore"
函数中输入 input()
时,我想从回收站中恢复我删除的文件。
有没有办法在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
。你能帮我吗?
解决方法
这取决于您的操作系统。
Linux
就像将它从垃圾文件夹移动到原始路径一样简单。垃圾文件夹的位置因发行版而异,但通常都在此位置。
您可以使用 command line tool 或深入研究代码以获得一些想法。
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
。请参阅this article了解更多详情
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())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。