DEV Community

Cover image for python pathlib
bluepaperbirds
bluepaperbirds

Posted on

3 2

python pathlib

With the Python programming language, you can deal with files. Some things you can do with Python are read files, write files, create files and much more.

If you worked with files in Python, you know that dealing with Paths can be quite cumbersome. On top of that paths are written differently on systems like Windows () or Mac (/)

You may be familiar with having to deal with double slashes and the like:

b = "c:\\stuff\\morestuff\\furtherdown\\THEFILE.txt"

Meet the pathlib module, which prevents you from writing code like this.

Pathlib

Pathlib makes working with paths and files in general easier. Instead of those ugly double slashes you can write elegant and readable Python code.
To get your home directory:

>>> import pathlib
>>> pathlib.Path.home()

The current working directory:

>>> import pathlib
>>> pathlib.Path.cwd()

You can simply add slashes for subdirectories

>>> pathlib.Path.home() / 'Desktop' / 'pama'

To define a filepath you can do this:

>>> filename = pathlib.Path.home() / 'Desktop' / 'files' / 'test.txt'
>>> filename

So you can use that path (filename) to read files as you would normally do:

>>> filename = pathlib.Path.home() / 'rdp.txt'
>>> with open(filename, mode='r') as f:
...     data = f.readlines()
... 
>>> data

You can even read files with one liner:

data = pathlib.Path(pathlib.Path.home() / 'rdp.txt').read_text()

To get the extension, name or parent of a path is also super easy:

>>> path = pathlib.Path.home() / 'Desktop' / 'files' / 'test.txt'
>>> path.name
'test.txt'
>>> path
PosixPath('/home/tux/Desktop/files/test.txt')
>>> path.parent
PosixPath('/home/tux/Desktop/files')
>>> path.suffix
'.txt'
>>> path.stem
'test'
>>>

Related links:

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay