
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are .pyc Files in Python
We usually write programs in Python and save the file with .py extension. However, there is another file type called .pyc, which is automatically generated by the Python interpreter while executing the source code.
What is a .pyc File?
When you execute a Python program, the Python interpreter doesn't directly execute the .py file; instead, it parses the source code, compiles it into bytecode(a low-level representation of the Python source code), and stores it as the .pyc file. Further, this bytecode is executed with the Python Virtual Machine (PVM).
A .pyc file is usually created when a Python program is executed for the first time or when a module is imported. Some of the benefits of storing byte codes in .pyc files are -
- By storing bytecode in a .pyc file, Python programs can run faster as the interpreter doesn't have to repeatedly recompile the source code.
- Once a .pyc file is generated, Python can load and execute this bytecode multiple times until the source code remains the same.
The name of the .pyc files includes the version of Python that generated them. For example, module.cpython-39.pyc for Python 3.9.
How do ".pyc" Files Work?
Python stores the .pyc files in a special directory called __pycache__, which is located in the same directory as the source code. When you import a module in Python, the interpreter checks if a .pyc file exists in the __pycache__ directory. If it is there, Python loads the bytecode from the .pyc file directly by skipping the compilation step. In case if it is not there, the interpreter recompiles the .py file.
Managing and Deleting .pyc Files
We cannot run .pyc files directly from the command line like we execute the .py files. If the corresponding source code exists, the .pyc file will automatically be executed when the Python interpreter runs or when a module is imported.
You will not need to manually manage or delete the .pyc files because Python will regenerate them when needed. In case if you are troubleshooting issues or cleaning up unnecessary files, you can delete the .pyc files. Following discusses the method that can be used to delete .pyc files.
The find method is a command-line utility for searching for files in a directory, to find all of the .pyc files, and use its delete option to remove all of them. Follow the below commands -
#To find all .pyc files in all folders find. -name '*.pyc' # To delete the files find. -name '*.pyc' -delete