# Joining paths
p = Path("/home/max") / "docs" / "report.pdf"
# Replace filename or extension
p.with_name("new_file.txt")
p.with_suffix(".md")
p.exists() # True/False
p.is_file() # True if file
p.is_dir() # True if directory
p.is_symlink() # True if symlink
# Read / write text
p.write_text("Hello World")
content = p.read_text()
# Read / write bytes
p.write_bytes(b"binary data")
data = p.read_bytes()
# Make directories
Path("new/folder").mkdir(parents=True, exist_ok=True)
# Remove file
p.unlink()
# Rename / move
p.rename("new_name.txt")
p.replace("some/other/location.txt")
# Match all .txt files
for file in Path("docs").glob("*.txt"):
print(file)
# Recursive glob
for file in Path("docs").rglob("*.txt"):
print(file)
p = Path("docs/../report.pdf")
p.resolve() # Absolute normalized path
The iterdir() method allows you to iterate over all the files and subdirectories in a folder.
It is particularly useful for processing all files in a directory or performing operations on each
entry.
Since iterdir() returns an iterator,
entries are retrieved on-demand as you go through the loop.
# My Default way for Python to find the current App folder
APP_DIR:Path[str] = Path(__file__).resolve().parent
p = Path("docs")
# Basic Iteration & Print Results
for item in p.iterdir():
print(item)
# Filter files only
for f in Path(".").iterdir():
if f.is_file():
print(f)
# Filter directories only
for d in Path(".").iterdir():
if d.is_dir():
print(d)
# Sorted
for entry in sorted(Path(".").iterdir()):
print(entry.name)
# Filter by extension
for f in Path(".").iterdir():
if f.suffix == ".txt":
print(f)
# List comprehension
files = [f.name for f in Path(".").iterdir() if f.is_file()]
| Method | Scope | Example |
|---|---|---|
iterdir() |
Direct children only | Path(".").iterdir() |
glob("*.py") |
Pattern-matching, 1 level deep | Path(".").glob("*.py") |
rglob("*.py") |
Recursive search | Path(".").rglob("*.py") |
| Method | Arguments | Default | Explanation |
|---|---|---|---|
mkdir() |
mode, parents, exist_ok | 0o777, False, False | Create a directory. parents=True creates parent directories. exist_ok=True ignores if directory exists. |
rmdir() |
- | - | Remove empty directory. Raises OSError if not empty. |
unlink() |
missing_ok | False | Delete a file. missing_ok=True ignores if file missing. |
rename() |
target | - | Rename or move file. Overwrites not allowed if exists. |
replace() |
target | - | Rename or move file. Overwrites if target exists. |
touch() |
mode, exist_ok | 0o666, True | Create empty file. exist_ok=True ignores if file exists. |
open() |
mode, encoding | "r", None | Open file handle like open(). |
read_text() |
encoding, errors | None, None | Read file as string. |
write_text() |
data, encoding, errors | - | Write string to file. |
glob() |
pattern | - | Pattern match files in directory. |
rglob() |
pattern | - | Recursive pattern match files. |
iterdir() |
- | - | Iterate over directory entries (direct children only). |