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.

Easy Python 3.6+ Aug 9, 2026 Git + Python 14 views 0 copies

Python code

16 lines
Python 3.6+
import 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

stdout
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

  1. Use `git show --name-only --format=` HEAD to list files in the last commit
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.