What is the difference between .py and .pyc files?

PythonFile

Python Problem Overview


I have noticed .pyc files spontaneously being generated when some .py file of the same name gets run. What is the difference between .py and .pyc files?

Also, I find that having .pyc files lying around clutters up space. Should one delete .pyc files? Or is there a benefit and/or necessity to having them around?

UPDATE: Here are 2 answered questions that are related to my question

https://stackoverflow.com/questions/2998215/if-python-is-interpreted-what-are-pyc-files

https://stackoverflow.com/questions/3878479/python-pyc-files-main-file-not-compiled

This Question is not a Duplicate

Reason 1: Because I am asking what the difference between these two files are. The question S.Lott found named 'If Python is interpreted, what are .pyc files?' is not asking what the difference between .py and .pyc files are. It is asking what .pyc files are.

Reason 2: Because my secondary questions 'Should one delete .pyc files? Or is there a benefit and/or necessity to having them around?' provide even more information on .pyc files and how one should handle them.

Reason 3: Because when a beginner Python programmer like myself wants to find out What is the difference between .py and .pyc files? , they will have no problem finding out the answer as they will be guided directly to my question. This helps reduce search time since the question is right to the point.

Python Solutions


Solution 1 - Python

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

Solution 2 - Python

Python compiles the .py and saves files as .pyc so it can reference them in subsequent invocations.

There's no harm in deleting them, but they will save compilation time if you're doing lots of processing.

Solution 3 - Python

"A program doesn't run any faster when it is read from a ".pyc" or ".pyo" file than when it is read from a ".py" file; the only thing that's faster about ".pyc" or ".pyo" files is the speed with which they are loaded. "

http://docs.python.org/release/1.5.1p1/tut/node43.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpyloniconView Question on Stackoverflow
Solution 1 - PythonmipadiView Answer on Stackoverflow
Solution 2 - Pythonmeder omuralievView Answer on Stackoverflow
Solution 3 - PythonNameView Answer on Stackoverflow