Technical | How to Recover a Deleted/Overwritten Python File?

TL;DR: If you have run the Python program at least once like I did, you can find the pyc file in pycache folder and use a decompiler to decompile it back to a Python file.

I recently started to take Harvard CS50’s latest AI course and just finished a programming assignment. Before I submitted and celebrated my success, I accidentally overwrote the file and lost hours of work. It turned out I opened the same file twice and accidentally saved the earlier version.

Degrees - CS50's Introduction to Artificial Intelligence with Python

Before I mourned my loss, I knew from instinct that, there must be some way to recover the file, because I ran the file using a Python interpreter in the terminal 5 seconds ago.

I did some research and found the solution: In the __pycache__ folder, you will see a compiled .pyc file that is compiled by the Interpreter. Mine is degrees.cpython-36.pyc

According to Python’s documentation:

Python source code is compiled into bytecode, the internal representation of a Python program in the CPython interpreter. The bytecode is also cached in .pyc files so that executing the same file is faster the second time (recompilation from source to bytecode can be avoided). This “intermediate language” is said to run on a virtual machine that executes the machine code corresponding to each bytecode.

Find a decompiler that works with your Python version and and decompile it back to the Python file. I used cross-version Uncompyle6 and it worked perfectly.

However, if you haven’t run your program or don’t find a pyc file, you unfortunately need to dig in your computer’s memory or drive and go from there. There are lots of softwares you can try for that.

And of course, the better practice is to use Git for version control in the first place :)

Happy coding!

Get in touch:

Athena Xiao | LinkedIn



Continue Learning