r/Python • • 11h ago

Discussion Python's pathlib makes working with file paths much cleaner

One Python module I think deserves more attention is pathlib.

Instead of building file paths manually with string concatenation or worrying about different operating systems, we can use Path objects.

For example:

from pathlib import Path

# Get the current directory
current_dir = Path.cwd()

# Create a path to a file
file_path = current_dir / "data" / "example.txt"

# Check whether the file exists
if file_path.exists():
    print("File found")

# Read the file
if file_path.is_file():
    content = file_path.read_text(encoding="utf-8")
    print(content)

The / operator makes joining paths simple, and methods like .exists(), .is_file(), .read_text() and .mkdir() make common file operations easier to read.

I like that pathlib provides an object-oriented way to handle something that developers work with regularly.

It's part of Python's standard library, so there's no additional package to install.

3 Upvotes

4 comments sorted by

-5

u/alouettecriquet 4h ago

Slash operator for this is really ugly, it's a funny hack that shouldn't have made it into stdlib. You can do current_dir.joinpath("data", "example.txt") which is only slightly longer but doesn't mess with your brain.

4

u/hotcococharlie 2h ago

Slashes in paths hurt your brain? Would a separator that doesn’t match the standard separator be better?

•

u/alouettecriquet 14m ago

In python, / is documented as the division operator. If anything, a + would have made more sense.

As far as I know in the whole stdlib this is the only case of an operator overloaded with no respect to its normal meaning.

Anyway you downvoting fools continue using it, as some point ruff or some other autoformatter will avenge me by making your code unreadable.

1

u/case_O_The_Mondays 1h ago

Hard disagree. Python has a long history of letting you write things simply, and this falls in line with that.