import pathlib is a Python import that provides object-oriented filesystem paths. Prefer pathlib.Path over os.path for modern code; it's more readable and handles cross-platform paths automatically.
# Python # description: create paths, check existence, read files from pathlib import Path # Create a path object p = Path("data/config.txt") # Check if file exists if p.exists(): print(f"File exists at {p.resolve()}") # Get file properties print(f"Size: {p.stat().st_size} bytes") # Read file contents content = p.read_text() # Write to file output = Path("output.txt") output.write_text("Hello, World!") # Iterate over files in directory for file in Path(".").glob("*.py"): print(file.name)
Path(path): create path objectp.exists(): check if path existsp.is_file(): check if it's a filep.is_dir(): check if it's a directoryp.resolve(): get absolute pathp.name: filename with extensionp.stem: filename without extensionp.suffix: file extensionp.parent: parent directoryp.read_text(): read file as stringp.write_text(text): write string to filep.mkdir(parents=True): create directoryp.glob(pattern): find files matching patternp.iterdir(): iterate over directory contents