Better way to handle paths in python
Dilli Babu R
Posted on February 22, 2021
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)
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
But, a better way to handle paths would be
Using Path
from pathlib
first lets import Path
from pathlib
from pathlib import Path
Then we will initiate path like follows, note we use /
even in Windows OS instead of \\
.
folder_path = Path('C:/Users/dr/Documents')
Then to append path we simply have to use /
like so
file_path = folder_path / file_name
Even if we have a long paths it would be easier to write and read.
long_file_path = root / folder_a / folder_b / filename
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
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
January 31, 2022