Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • AI
  • 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()
1 month ago Permalien
cluster icon
  • Regex : Regex Essentials: Overview Regular expressions (regex) are a language for defining text search patterns. Python’s re module provides functions like...
  • Temporary Files and Directories : Temporary Files and Directories Automation scripts often need scratch space for intermediate data without cluttering the filesystem or risking name c...
  • Declarative Logging : Declarative Logging Configuration Declarative configuration separates setup from code, making it easier to maintain and adjust. Python’s logging.conf...
  • Classes and Objects : Classes and Objects Beyond Built-ins: Python lets you define your own data types using class. Class: A blueprint or template for creating objects. De...
  • 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...


(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