How to List Changed Files in the Last Git Commit with Python
Runs `git diff --name-only HEAD~1 HEAD` via subprocess to list the names of files changed in the most recent commit.
Python code
16 linesimport subprocess
def list_changed_files():
result = subprocess.run(
["git", "diff", "--name-only", "HEAD~1", "HEAD"],
capture_output=True,
text=True,
check=True
)
files = result.stdout.strip().splitlines()
return files
if __name__ == "__main__":
changed = list_changed_files()
for file in changed:
print(file)
Output
src/main.py
README.md
tests/test_app.py
How it works
The script invokes git diff --name-only HEAD~1 HEAD, which prints only the names of files changed between the previous commit and the current one. subprocess.run with capture_output=True and text=True captures stdout as a string; check=True ensures a non-zero exit code raises an exception. stdout.strip().splitlines() removes trailing newline and splits into a list of file paths.
Common mistakes
- Using `git diff` without `--name-only`, which also outputs other metadata
- Forgetting `check=True`, so command failures go unnoticed
- Assuming the script runs inside a Git repository; it raises `CalledProcessError` otherwise
Variations
- Use `git show --name-only --format=` HEAD to list files in the last commit
- Use `git diff --name-only --diff-filter=ACMRTUXB HEAD~1 HEAD` to filter by change type
Real-world use cases
- Automating changelog generation by listing files modified in each release commit.
- Triggering selective CI tests only for modules whose files changed in the latest PR.
- Building deployment scripts that conditionally rebuild parts of a service when relevant files change.
Sponsored
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
Keep learning
Related tutorials and quizzes for this topic.