Using .gitignore
Learn how to exclude unnecessary files from your Git repositories: virtual environments, build artifacts, and more.
What Is .gitignore?
A .gitignore file is a plain text file placed at the root of your Git repository. It tells Git which files and directories to completely ignore: they will not be tracked, staged, or committed.
Why Does .gitignore Matter?
Common Files to Exclude
Core Pattern Syntax
The .gitignore file uses glob-style patterns to match files and directories. Each line specifies one pattern.
The Golden Rule
venv/ vs __pycache__/
| venv/ | __pycache__/ | |
|---|---|---|
| What is it? | Python virtual environment | Compiled bytecode cache |
| Contains | Python interpreter + all packages | .pyc files (auto-generated) |
| Typical size | 50 MB to 500+ MB | A few KB per module |
| Reproducible? | Yes, via pip install -r requirements.txt | Yes, auto-regenerated on import |
| Must ignore? | Absolutely | Absolutely |
Build Artifacts to Exclude
Step-by-Step Setup
Example 1: Minimal Python .gitignore
Example 2: Adding Build Artifacts
Example 3: Negation Patterns
Seeing It In Action
Advanced Wildcards
| Pattern | Matches | Does Not Match |
|---|---|---|
| *.pyc | module.pyc, test.pyc | module.py |
| logs/ | logs/ directory anywhere | a file named "logs" |
| /debug.log | debug.log at root only | src/debug.log |
| **/*.tmp | .tmp files in any subdirectory | files without .tmp extension |
| doc/**/*.pdf | doc/a.pdf, doc/v1/b.pdf | notes/c.pdf |
Common Mistakes
Summary Cheat Sheet
| Category | Patterns | Why Ignore? |
|---|---|---|
| Virtual Environments | venv/, env/, .venv/ | Huge, reproducible via pip |
| Bytecode | __pycache__/, *.pyc | Auto-generated on import |
| Build Artifacts | build/, dist/, *.egg-info/ | Regenerated on build |
| Secrets | .env, *.key | Security risk |
| IDE / OS | .idea/, .vscode/, .DS_Store | Machine-specific |
Question 1 of 5
What is the primary purpose of a .gitignore file?
Question 2 of 5
You added venv/ to your .gitignore, but the venv directory still appears in git status. What is the most likely reason?
Question 3 of 5
Which pattern would ignore all .pyc files in every subdirectory of your project?
Question 4 of 5
Your .gitignore contains these two lines:
*.log
!error.log
Which statement is correct?
Question 5 of 5
Why should you always commit the .gitignore file itself to the repository?