DEV Community

Dilli Babu R
Dilli Babu R

Posted on

Better way to handle paths in python

What this is about?

You might have seen python code handling paths like this.

folder_path = 'C:\\users\\dr\\Documents'
# in unix based machines like below
# folder_path = "/home" + "/" + "dr"
file_name = 'test.txt'
file_path = folder_path + '\\' + file_name

with open(file_path) as file_data:
    do_something_with(file_data)
Enter fullscreen mode Exit fullscreen mode

of course, this will work. But, if we want our program to work in other OS such as Mac or Linux, then the code will fail, because Windows handles path differently compared to UNIX based Operating Systems.

So, another way is to use join method from os.path module like below.

import os
file_path =  os.path.join("C:\\", "users", "dr", "Documents", "test.txt")
print(file_path) # C:\users\dr\Documents
Enter fullscreen mode Exit fullscreen mode

But, a better way to handle paths would be

Using Path from pathlib

first lets import Path from pathlib

from pathlib import Path
Enter fullscreen mode Exit fullscreen mode

Then we will initiate path like follows, note we use / even in Windows OS instead of \\.

folder_path = Path('C:/Users/dr/Documents')
Enter fullscreen mode Exit fullscreen mode

Then to append path we simply have to use / like so

file_path = folder_path / file_name
Enter fullscreen mode Exit fullscreen mode

Even if we have a long paths it would be easier to write and read.

long_file_path = root / folder_a / folder_b / filename
Enter fullscreen mode Exit fullscreen mode

this will work properly in Windows, Mac & Linux, we don't have to worry about \\ or /.

Apart from this advantage, Path also provides lot of functions such as is_file, is_dir, mkdir, which we normally use from os.path module.

# few methods
import Path from pathlib
path = Path("/home/dr")
path.exists() # returns True if folder exists else False
path.home() # "/home/dr"
path.is_dir() # True
path.is_file() # False
path.mkdir() # create folder
# and a lot more
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
juancarlospaco profile image
Juan Carlos

The problem with pathlib is that is very very slow,
pathlib can be more than 25 ~ 50x slower than a normal str.

Collapse
 
dillir07 profile image
Dilli Babu R

That true, but for most of our normal use cases this shouldn't be a problem, unlike performance critical code. Thanks for the link :)