How to Build an argparse CLI That Filters File Lines by Keyword in Python
This Python script is a command-line tool built with argparse that reads a text file and prints only the lines that contain (or don't contain) a given keyword.
Python code
35 linesimport argparse
import sys
def main():
parser = argparse.ArgumentParser(description="Filter lines from a file by keyword.")
parser.add_argument("input", type=str, help="File to read")
parser.add_argument("keyword", type=str, help="Keyword to filter lines")
parser.add_argument("--contains", action="store_true", help="Keep lines containing keyword (default)")
parser.add_argument("--not-contains", action="store_true", help="Keep lines NOT containing keyword")
args = parser.parse_args()
exclusion_mode = args.not_contains
if args.contains and args.not_contains:
print("Error: cannot combine --contains and --not-contains", file=sys.stderr)
sys.exit(1)
try:
with open(args.input, "r") as f:
lines = [line.rstrip("\n") for line in f]
except FileNotFoundError:
print(f"Error: file '{args.input}' not found", file=sys.stderr)
sys.exit(1)
filtered = []
for line in lines:
is_match = args.keyword in line
keep = not is_match if exclusion_mode else is_match
if keep:
filtered.append(line)
for line in filtered:
print(line)
if __name__ == "__main__":
main()
Output
$ python filter.py data.txt 'error' --contains
2025-01-01 10:00 error: disk full
2025-01-01 10:05 error: timeout
$ python filter.py data.txt 'error' --not-contains
2025-01-01 09:59 info: startup complete
2025-01-01 10:02 warning: low memory
How it works
The argparse module handles command-line parsing: positional arguments input and keyword are required, while --contains and --not-contains are optional flags. The script reads all lines with a context manager (with open) so the file is always closed properly, and line.rstrip("\n") removes the trailing newline. It then checks membership with keyword in line; exclusion_mode flips the match logic when --not-contains is used. The script exits with error messages to stderr for conflicting flags or a missing file, keeping the behavior predictable for scripting.
Common mistakes
- Combining `--contains` and `--not-contains` without a validation check
- Forgetting to strip newline characters, leading to unexpected matches or output
- Using `FileNotFoundError` only but not handling permissions (PermissionError)
- Not using `file=sys.stderr` for error messages, polluting stdout
Variations
- Use `filter(line for line in lines if keyword in line)` for a cleaner one-liner
- Add a `--case-insensitive` flag to handle case variations
Real-world use cases
- Searching for specific error keywords in application log files from the command line.
- Preprocessing data files by keeping only rows that match (or exclude) certain markers before analysis.
- Automating QA checks by filtering test output for pass/fail strings in a CI pipeline.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.