Helper Functions
Step 6: Implement Helper Methods
Now, we'll implement helper methods for each of the actions (clear_bin
, recycle_file
, recycle_all
, and search_file
).
6.1: clear_bin
Method
This method clears the recycle bin using the winshell.recycle_bin().empty()
function.
def clear_bin(self):
recycle_bin = winshell.recycle_bin()
items = len(list(recycle_bin))
if items != 0:
recycle_bin.empty(confirm=True, show_progress=True, sound=True)
return "Recycle bin has been cleared."
else:
return "The recycle bin is already empty."
empty()
: Empties the recycle bin.The method checks if there are items in the recycle bin before attempting to clear it.
6.2: recycle_file
Method
This method restores a specific file from the recycle bin using its file path.
def recycle_file(self, file_path: str):
try:
winshell.undelete(file_path)
return f"The file {file_path} has been restored from the recycle bin."
except Exception as e:
return f"Error restoring file: {str(e)}"
undelete(file_path)
: Restores the file from the recycle bin by its original path.
6.3: recycle_all
Method
This method restores all items in the recycle bin by calling undelete()
on each item.
def recycle_all(self):
try:
for item in winshell.recycle_bin():
winshell.undelete(item.original_filename())
return "All files have been restored from the recycle bin."
except Exception as e:
return f"Error restoring files: {str(e)}"
item.original_filename()
: Retrieves the original file path of each item in the recycle bin.
6.4: search_file
Method
This method searches for files in the recycle bin by their name (or partial name). It returns a list of matching files.
def search_file(self, file_name: str):
similar_files = []
for item in winshell.recycle_bin():
if file_name.lower() in os.path.basename(item.original_filename()).lower():
similar_files.append({
"file_name": os.path.basename(item.original_filename()),
"file_path": item.original_filename()
})
if similar_files:
return f"Found files: {similar_files}"
else:
return f"No files matching {file_name} found in recycle bin."
os.path.basename()
: Extracts the file name from the full path.We use case-insensitive matching to check if the given
file_name
is part of any files in the recycle bin.
Last updated