TGViewer
Learn Python Coding Learn Python Coding @pythonre · 40.9K subscribers
Post #8826 1.36K
import pathlib
import shutil

# --- Setup: Create a temporary directory and files for the demo ---
# We use a relative path './temp_docs' so it works anywhere
docs_dir = pathlib.Path("temp_docs")
if docs_dir.exists():
shutil.rmtree(docs_dir) # Clean up from previous runs
docs_dir.mkdir()

# Create dummy files
(docs_dir / "report.txt").write_text("This is a test report.")
(docs_dir / "notes.txt").write_text("Some important notes.")
# ----------------------------------------------------------------

# 1. Create a Path object for our report file
file_path = docs_dir / "report.txt"

# 2. Inspect Path Components
print(f"File Name: {file_path.name}")
print(f"Parent Directory: {file_path.parent}")
print(f"File Stem: {file_path.stem}")
print(f"File Suffix: {file_path.suffix}")

# 3. Check Path Properties
print(f"Exists: {file_path.exists()}")
print(f"Is File: {file_path.is_file()}")
print(f"Is Directory: {file_path.is_dir()}")

# 4. Manipulate Paths and prepare for renaming/moving
archive_dir = docs_dir / "archive"
archive_dir.mkdir() # Create the 'archive' subdirectory
new_file_path = archive_dir / "old_report.txt"
print(f"New Path: {new_file_path}")

# To demonstrate renaming, let's rename the original file
file_path.rename(new_file_path)

# 5. Iterate over the original directory to find files
for found_file in sorted(docs_dir.glob("*.txt")):
print(f"Found File: {found_file.name}")

# 6. Demonstrate a copy operation
# `pathlib` itself doesn't have a copy method, but works perfectly with `shutil`
source_file = docs_dir / "notes.txt"
destination_file = archive_dir / "notes_backup.txt"
shutil.copy(source_file, destination_file)
print("File copied successfully!")


# --- Cleanup: Remove the temporary directory ---
shutil.rmtree(docs_dir)
# -----------------------------------------------


This self-contained script first sets up a realistic file structure, then demonstrates the power and simplicity of pathlib to inspect, manipulate, and manage files and directories, cleaning up after itself when it's done.

━━━━━━━━━━━━━━━
By: @DataScience4 ✨
  • ❤ 6
  • 🔥 2
  • 👍 1
More from @pythonre
  1. Oct 17, 2026😰 15-Hour "Python for Data Science" Course ⚡️ Learn Python for Data Science https://enghu…
  2. Oct 13, 2026https://substack.com/@husseinsheikho?utm_source=share&utm_medium=android&r=3hwnr8 Follow m…
  3. Oct 10, 2026📚 Download 10 Python books for FREE: 1. Think Python — O’Reilly https://t.co/X7y3pX68IW 2…
  4. Oct 7, 2026Python Lists: A Quick Reference 🐍 * Definition: Lists are ordered, mutable collections th…
  5. Oct 7, 2026📱 270 tools for Python developers The repository contains: 🫡 Linters and formatters; 🫡…
  6. Oct 7, 2026Hands On Python Data Science - Data Science Bootcamp Master Python for Data Science with R…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →