difference between .py and .pyc file in python language


Difference Between .Py And .Pyc File In Python Language

Needs of .py and .pyc file in python

After writing the python code, the file is first saved as a .py file. 

Difference Between .Py And .Pyc File In Python Language
Difference Between .Py And .Pyc File In Python Language

So .py files consist of the source code. On the contrary, .pyc file consists of the bytecode of the program. This bytecode is obtained after compiling the source code in the .py file. These .pyc files are not generated for all the files that are run , instead it is generated only for the files that are imported.

Prior to execution of a .py file , the python interpreter looks for compiled files. If it is found, then that file is executed, else it looks for .py file. If it is found then it is compiled to generated .pyc file and then executed. 

Basically having .pyc file reduces the time required for compilation.

For example:

//Program to add 2 numbers:-

a=2 

b=3

sum = a+ b

print(sum)

If this program is saved with the name ‘add’ then it will be stored as ‘add.py’.

On opening the file ‘add.py’ , the above code will be displayed. When the file ‘add.py’ is executed , the above given code is first turned into byte code by the compiler to ‘add.pyc’ file.

Also see : scope in python

Need of .pyc file

The .py file has direct access to source code. If we are working on some highly confidential project , the source code should not be leaked. So we need to compile it into a .pc file. 

Python has a built-in class library which helps to compile .py files into .pyc files.

Also read : benefit of python

This is the py_compile module.This function can be useful when installing modules for shared use, especially if some of the users may not have permission to write the byte-code cache files in the directory containing the source code.

py_compile.compile(file, cfile=None, dfile=None, doraise=False, optimize=-1, invalidation_mode=PycInvalidationMode.TIMESTAMP, quiet=0)

  • File – path to the .py file
  • cfile – name and path of compiled .pyc file.
  • dfile – name of source file in error message.
  • Doraise – true/false. If true, an error will be raised. 

Also see : Database in python

Name of Intern who share this Task:

Athira lonappan

Github Link : https://github.com/athira1402/Task

I am Mr. Sachin pagar the founder of Pythonslearning, a Passionate Educational Blogger and Author, who love to share the informative content on educational resources.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

google ads

Pythonslearning protected By DMCA

NEWS ADS