在python中从回收站还原文件

2024-10-06 14:02:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在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。你能帮帮我吗


Tags: thetonameintesttxtindexbin
1条回答
网友
1楼 · 发布于 2024-10-06 14:02:27

这取决于您的操作系统

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上,除了垃圾路径是~/.Trash之外,您可以执行与Linux相同的操作

import subprocess as sp

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

请注意,macOS将有关文件的信息存储在~/.Trash/.DS_Store,而Linux将文件存储在/home/USERNAME/.local/share/Trash/info/。如果您不知道文件的原始路径,这将非常有用

窗口

你必须使用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())

相关问题 更多 >