Junior
What is the difference between .py and .pyc files?
sobes.tech AI
Answer from AI
.py— this is source code in Python, written by a human and readable by the interpreter..pyc— this is bytecode compiled by the interpreter from a.py` file to speed up subsequent runs.
The Python interpreter automatically compiles .py files into .pyc upon the first import of a module and saves them to avoid recompiling on each subsequent run. .pyc files are stored in the __pycache__ directory or alongside the corresponding .py file in older versions.
# Example of a `.py` file content
def greet(name):
print(f"Hello, {name}!")
# Bytecode from a `.pyc` file (not directly readable)
# c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00s\x0e\x00\x00\x00d\x00\x00GHd\x01\x00k\x02\x00\x83\x01\x00\x00d\x02\x00R\x00\xfa\x0bgreet.py\x05\x00\x00\x00s\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00C\x00\x00\x00s\x05\x00\x00\x00\x83\x00\x00\x00\x00Sq\x00\x00\x00s\x0c\x00\x00\x00\\x01\x00\x00\x00\x00\x01\x00\x00\x00r\x02\x00\x00\x00r\x02\x00\x00\x00\xfa\x0b<frozen greet>\x01\x00\x00\x00s\x08\x00\x00\x00\xe9\x00\x00\x00\x00r\x03\x00\x00\x00r\x04\x00\x00\x00r\x0b\x00\x00\x00r\x04\x00\x00\x00N\x86\x04\x00\x00\x00GHGHGHGHGHGHGHGHGHGHGHGHGHGHGHGHGHGHG\x0c\x12\x00\x00\x00s\x00\x00\x00\x00
In summary:
| File | Description | Purpose | Readability |
|---|---|---|---|
.py |
Source code | Development, writing logic | High (by humans) |
.pyc |
Compiled bytecode | Speed up execution | Low (by machines) |
The presence of .pyc does not affect code execution, as the interpreter uses them only for module loading optimization. If a .py file is modified, the .pyc file is automatically regenerated.