python – Ignore .pyc files in git repository-ThrowExceptions

Exception or error:

How can I ignore .pyc files in git?

If I put it in .gitignore it doesn’t work. I need them to be untracked and not checked for commits.

How to solve:

Put it in .gitignore. But from the gitignore(5) man page:

  ·   If the pattern does not contain a slash /, git treats it as a shell
       glob pattern and checks for a match against the pathname relative
       to the location of the .gitignore file (relative to the toplevel of
       the work tree if not from a .gitignore file).

  ·   Otherwise, git treats the pattern as a shell glob suitable for
       consumption by fnmatch(3) with the FNM_PATHNAME flag: wildcards in
       the pattern will not match a / in the pathname. For example,
       "Documentation/*.html" matches "Documentation/git.html" but not
       "Documentation/ppc/ppc.html" or

So, either specify the full path to the appropriate *.pyc entry, or put it in a .gitignore file in any of the directories leading from the repository root (inclusive).


You should add a line with:


to the .gitignore file in the root folder of your git repository tree right after repository initialization.

As ralphtheninja said, if you forgot to to do it beforehand, if you just add the line to the .gitignore file, all previously committed .pyc files will still be tracked, so you’ll need to remove them from the repository.

If you are on a Linux system (or “parents&sons” like a MacOSX), you can quickly do it with just this one line command that you need to execute from the root of the repository:

find . -name "*.pyc" -exec git rm -f "{}" \;

This just means:

starting from the directory i’m currently in, find all files whose
name ends with extension .pyc, and pass file name to the command git rm -f

After *.pyc files deletion from git as tracked files, commit this change to the repository, and then you can finally add the *.pyc line to the .gitignore file.

(adapted from


You have probably added them to the repository before putting *.pyc in .gitignore.
First remove them from the repository.


i try to use the sentence of a prior post and don’t work recursively, then read some help and get this line:

find . -name "*.pyc" -exec git rm -f "{}" \;

p.d. is necessary to add *.pyc in .gitignore file to maintain git clean

echo "*.pyc" >> .gitignore



Thanks @Enrico for the answer.

Note if you’re using virtualenv you will have several more .pyc files within the directory you’re currently in, which will be captured by his find command.

For example:


I suppose it’s harmless to remove all the files, but if you only want to remove the .pyc files in your main directory, then just do

find "*.pyc" -exec git rm -f "{}" \;

This will remove just the app.pyc file from the git repository.

Leave a Reply

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