Lenovo 360
Lenovo 360

Reputation: 647

Restoring files from the recycle bin in python

Is there any to restore files from the recycle bin in python?

Here's the code:

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

Here when I type "restore" in the input() function, I want to restore my deleted file from the recycle bin.

Is there any way to achieve this in python?

It would be great if anyone could help me out.

EDIT:

Thanks for the answer @Kenivia, but I am facing one small issue:

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())

When I run this code, I get an error: ValueError: 'C:\\test\\Untitled_1.txt' is not in list. Can you please help me out?

Upvotes: 4

Views: 2327

Answers (2)

Amir Dagan
Amir Dagan

Reputation: 11

Google Colab (you are the root user)

Import the shell utility for Python:

import shutil

Move the file from trash to a selected destination:

shutil.move('/root/.local/share/Trash/files/<deleted-file>', '<destination-path>')

Upvotes: 0

Kenivia
Kenivia

Reputation: 384

It would depend on your operating system.

Linux

it's as simple as moving it from the trash folder to the original path. The location of the trash folder differs from distro to distro, but this is where it typically is.

There is a command line tool that you can use, or dig through the code to get some ideas.

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

On macOS, you do the same thing as you do in Linux, except the trash path is ~/.Trash

import subprocess as sp

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

Note that macOS stores information about the files at ~/.Trash/.DS_Store, where Linux stores them at /home/USERNAME/.local/share/Trash/info/. This can be useful if you don't know the original path of the files.

Windows

you have to use winshell. See this article for more details

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())

Upvotes: 4

Related Questions