How do I create a .pyc file in Python?

A .pyc file is Python bytecode compiled from source code. Python provides two main modules to create .pyc files: py_compile for individual files and compileall for multiple files or directories.

Using py_compile Module

The py_compile module generates bytecode files from Python source files. Here's how to compile a single file ?

Compiling a Single File

import py_compile

# Create a sample Python file first
with open('demo.py', 'w') as f:
    f.write('print("Hello, World!")')

# Compile the file to .pyc
py_compile.compile('demo.py')
print("demo.py compiled successfully!")
demo.py compiled successfully!

Compiling Multiple Files

Use py_compile.main() to compile multiple files at once ?

import py_compile

# Create sample files
files = ['file1.py', 'file2.py', 'file3.py']
for i, filename in enumerate(files, 1):
    with open(filename, 'w') as f:
        f.write(f'print("This is file {i}")')

# Compile multiple files
py_compile.main(files)
print("All files compiled successfully!")
All files compiled successfully!

Using compileall Module

The compileall module is designed for batch compilation and library installation scenarios.

Compiling Individual Files

import compileall

# Create a sample file
with open('sample.py', 'w') as f:
    f.write('def greet(): return "Hello from sample!"')

# Compile the file
result = compileall.compile_file('sample.py')
print(f"Compilation successful: {result}")
Compilation successful: True

Compiling Entire Directory

import compileall
import os

# Create a directory with Python files
os.makedirs('test_dir', exist_ok=True)
with open('test_dir/module1.py', 'w') as f:
    f.write('def func1(): return "Module 1"')
with open('test_dir/module2.py', 'w') as f:
    f.write('def func2(): return "Module 2"')

# Compile all files in directory
result = compileall.compile_dir('test_dir')
print(f"Directory compilation successful: {result}")
Directory compilation successful: True

Command Line Usage

You can also use compileall from the command line ?

python -m compileall file1.py file2.py
python -m compileall directory_name

Comparison

Module Best For Features
py_compile Single files Simple, direct compilation
compileall Multiple files/directories Batch processing, library installation

Key Points

? .pyc files are stored in __pycache__ directory
? Compilation happens automatically when importing modules
? Manual compilation is useful for deployment and performance
? Both modules return True on successful compilation

Conclusion

Use py_compile for individual file compilation and compileall for batch operations. Both modules create .pyc files that improve Python startup performance by skipping the compilation step.

Updated on: 2026-03-26T21:53:08+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements