Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

Filesystem Paths/shaare/jvk1Ew

  • python
  • python

Working with Filesystem Paths in Python

  • Manipulating paths as plain strings is error-prone and OS-specific.
  • pathlib provides an object-oriented, cross-platform way to handle paths.
  • Path objects offer intuitive operators and methods for most filesystem tasks.

Limitations of String Paths and os.path

  • Using os.path.join, os.path.exists, etc., requires multiple function calls.
  • Code readability suffers when paths are manipulated as plain strings.
  • OS differences ("/" vs "\" separators) must be handled explicitly.

Creating and Combining Path Objects

  • Import Path from pathlib.
  • Create Path objects for directories and files.
  • Use the / operator to join path components cleanly.
from pathlib import Path

config_dir = Path(".")
filename = "settings.yaml"

print(config_dir, type(config_dir))

config_path = config_dir / filename
print(config_path.resolve())

Inspecting Path Properties

  • .exists(), .is_file(), .is_dir() check path state.
  • .parent, .name, .stem, .suffix expose components.
  • .resolve() returns the absolute, canonical path.
service_log = Path("/var/log/app/service.log")

print(f"Exists: {service_log.exists()}")
print(f"Is file? {service_log.is_file()}")
print(f"Is directory? {service_log.is_dir()}")
print(f"Parent: {service_log.parent}")
print(f"Name: {service_log.name}")
print(f"Stem: {service_log.stem}")
print(f"Suffix: {service_log.suffix}")
print(f"Resolved absolute path: {service_log.resolve()}")

Listing Directory Contents

  • .iterdir() yields immediate children of a directory.
  • .glob(pattern) finds entries matching a shell-style pattern.
  • Use "**/*.ext" in glob for recursive searches.
course_parent = Path("..")

print("Immediate children:")

for i, child in enumerate(course_parent.iterdir()):
    print(f"  {child.name} - {child.is_dir()}")
    if i >= 4: break

print("Python files recursively:")

for i, child in enumerate(course_parent.glob("**/*.ipynb")):
    print(f"  {child}")
    if i >= 10: break

Reading and Writing Files with Path

  • .write_text() and .read_text() handle simple text I/O.
  • Use p.open(mode="a") for more control (e.g., appending, binary mode).
  • Path methods automatically manage file open/close.
test_file = Path("demo.txt")

test_file.write_text("Hello, from pathlib!", encoding="utf-8")
print(f"Read back: {test_file.read_text(encoding="utf-8")}")

with test_file.open(mode="a", encoding="utf-8") as file:
    file.write("\nAppended line!")

print(f"Read back: {test_file.read_text(encoding="utf-8")}")

test_file.unlink()
1 month ago Permalink
cluster icon
  • The Iteration Protocol : The Iteration Protocol We use for item in sequence: all the time. But how does Python get each item? Iterable: An object that can be looped over. It...
  • Range, zip : Efficient Looping: range Creating large lists for loops is memory-intensive (e.g., list(range(1_000_000))). range() stores only start, stop, and step...
  • Generators : Generators Writing a class-based iterator requires __iter__() and __next__(), plus manual state management and StopIteration handling. Generator fu...
  • Functions: return vs yield : Functions: return vs yield Regular functions execute immediately, run to completion, and return a single value (or None). Generator functions retur...
  • For & While Loops : For & While Loops Python provides two main ways to repeat actions: for loops (for iterating over known sequences) and while loops (for repeating as lo...


(97)
Filter untagged links
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community