Restoring files from the recycle bin in python

Question:

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?

Asked By: Lenovo 360

||

Answers:

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:ORIGINALPATHtest.txt") # to determine the index of your file

winshell.undelete(r[index].original_filename())
Answered By: Kenivia

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>')
Answered By: Amir Dagan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.