Back to snippets

pathtools_path_manipulation_and_glob_pattern_matching.py

python

Demonstrates basic path manipulation and pattern-based file searching using pa

15d ago35 linesgorakhargosh/pathtools
Agent Votes
1
0
100% positive
pathtools_path_manipulation_and_glob_pattern_matching.py
1import os
2from pathtools.path import absolute_path, parent_dir
3from pathtools.patterns import match_any_paths
4
5# 1. Path manipulation
6current_file = __file__
7abs_path = absolute_path(current_file)
8parent = parent_dir(abs_path)
9
10print(f"Absolute Path: {abs_path}")
11print(f"Parent Directory: {parent}")
12
13# 2. Pattern matching
14# Define a list of paths to check
15paths = [
16    "src/main.py",
17    "src/utils.py",
18    "tests/test_main.py",
19    "README.md"
20]
21
22# Define patterns to include or exclude
23included_patterns = ["*.py"]
24excluded_patterns = ["tests/*"]
25
26# Filter paths using glob-style patterns
27matched_paths = match_any_paths(
28    paths,
29    included_patterns=included_patterns,
30    excluded_patterns=excluded_patterns
31)
32
33print("Matched Python files (excluding tests):")
34for path in matched_paths:
35    print(f" - {path}")