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
first lets import
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
Apart from this advantage,
Path also provides lot of functions such as
mkdir, which we normally use from
# 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