Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • Tags
  • Connexion

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()
2 months ago Permalien
cluster icon
  • Logging Anatomy : Python Logging Anatomy Python’s logging module has five core components: Loggers, Log Records, Handlers, Formatters and Filters. Loggers are hierar...
  • Lambda Functions : Lambda Functions Python functions defined with def allow multiple statements, clear naming, and support for docstrings, making them ideal for complex...
  • Running External Commands with subprocess.run : Running External Commands with subprocess.run DevOps automation often requires invoking existing CLI tools or scripts to leverage their functionality...
  • Python package and subpackage : Introduction to Packages (__init__.py) What is a Package? A Python package provides a way to structure a project's module namespace by using directori...
  • 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...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli