---
title: "How to Recover a file deleted with python?"  
description: "How to Recover a file deleted with python?"  
author: "Revati S Misra"  
published: 2023-07-24  
updated: 2023-07-25  
canonical: https://www.mindstick.com/forum/159255/how-to-recover-a-file-deleted-with-python  
category: "python"  
tags: ["file", "python", "recovery"]  
reading_time: 2 minutes  

---

# How to Recover a file deleted with python?

How to [Recover](https://answers.mindstick.com/blog/65/how-do-you-recover-from-a-google-penalty) a [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) [deleted](https://www.mindstick.com/forum/160487/how-to-remove-the-deleted-git-code-marker-in-scrollbar-in-visual-studio-2022) with [python](https://www.mindstick.com/articles/75378/simple-yet-useful-tips-when-using-python)?

## Replies

### Reply by Aryan Kumar

Sure, here is a Python code that you can use to recover a file deleted with Python:

Python

```plaintext
import os

def recover_deleted_file(file_path):
  """Recovers a deleted file from the specified path."""

  # Get the file's data.
  data = os.readlink(file_path)

  # Create a temporary file.
  temp_file_path = os.path.join(tempfile.gettempdir(), os.path.basename(file_path))

  # Write the file's data to the temporary file.
  with open(temp_file_path, "wb") as f:
    f.write(data)

  # Rename the temporary file to the original file path.
  os.rename(temp_file_path, file_path)

if __name__ == "__main__":
  file_path = "/path/to/deleted/file"

  recover_deleted_file(file_path)
```

This code first gets the file's data using the `os.readlink()` function. Then, it creates a temporary file using the `tempfile.gettempdir()` function and the `os.path.basename()` function. Then, it writes the file's data to the temporary file. Finally, it renames the temporary file to the original file path.

To use this code, you need to pass the path to the deleted file as the argument to the `recover_deleted_file()` function. For example, to recover the deleted file at the path `/path/to/deleted/file`, you would run the following code:

Python

```plaintext
recover_deleted_file("/path/to/deleted/file")
```

This code will recover the deleted file at the path `/path/to/deleted/file`.

Here are some additional things to keep in mind when using this code:

- The file that you want to recover must have been deleted recently. If the file has been deleted for a long time, the data may have been overwritten.
- This code only works if the file was deleted using the `os.remove()` function. If the file was deleted using another method, this code may not work.


---

Original Source: https://www.mindstick.com/forum/159255/how-to-recover-a-file-deleted-with-python

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
