How to Stage All Modified Files with git add -u in Python

Runs git add -u from Python to stage all modified and deleted tracked files, then prints the short status.

Easy Python 3.9+ Aug 9, 2026 Git + Python 15 views 0 copies

Python code

29 lines
Python 3.9+
import subprocess


def stage_all_modified_files(repo_path="."):
    """Run git add -u to stage all modified and deleted tracked files."""
    result = subprocess.run(
        ["git", "add", "-u"],
        cwd=repo_path,
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        print(f"Error staging files: {result.stderr.strip()}")
        return False

    # Show what's now staged
    status = subprocess.run(
        ["git", "status", "--short"],
        cwd=repo_path,
        capture_output=True,
        text=True,
    )
    print("Staged changes (M = modified, D = deleted):")
    print(status.stdout)
    return True


if __name__ == "__main__":
    stage_all_modified_files()

Output

stdout
Staged changes (M = modified, D = deleted):
 M file1.py
 D old_file.txt

How it works

The subprocess.run call executes git add -u in the specified repo path. -u stands for 'update' and stages changes to files that Git already tracks, including modifications and deletions but not new untracked files. The capture_output and text arguments let you read the result as text, and the return code check surfaces errors like a missing Git repo. Running git status --short afterward prints a concise list of staged changes, prefixed with 'M' for modified and 'D' for deleted.

Common mistakes

  • Forgetting to include -u, which would stage new untracked files too.
  • Not checking the return code, so errors appear silently.
  • Hardcoding the repo path instead of accepting it as a parameter.
  • Using text=True before Python 3.7, where it wasn't supported.

Variations

  1. Use `git add -A` if you also want to stage new untracked files.
  2. Parse status output with `git status --porcelain` for easier scripting.

Real-world use cases

  • Automating pre-commit staging in a CI script before running tests or linters.
  • Building a custom Git helper tool that stages changes based on filters.
  • Synchronizing a working directory with a remote by staging all changes programmatically.

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.