Better way to handle paths in python

dillir07

Dilli Babu R

Posted on February 22, 2021

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
šŸ’– šŸ’Ŗ šŸ™… šŸš©
dillir07
Dilli Babu R

Posted on February 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related