The os.path module is a very extensively used module that is handy when processing files from different places in the system. It is used for different purposes such as for merging, normalizing and retrieving path names in python . All of these functions accept either only bytes or only string objects as their parameters. Its results are specific to the OS on which it is being run.
This function gives us the last part of the path which may be a folder or a file name. Please the difference in how the path is mentioned in Windows and Linux in terms of the backslash and the forward slash.
import os # In windows fldr = os.path.basename("C:\\Users\\xyz\\Documents\\My Web Sites") print(fldr) file = os.path.basename("C:\\Users\\xyz\\Documents\\My Web Sites\\intro.html") print(file) # In nix* fldr = os.path.basename("/Documents/MyWebSites") print(fldr) file = os.path.basename("/Documents/MyWebSites/music.txt") print(file)
Running the above code gives us the following result −
My Web Sites intro.html MyWebSites music.txt
This function gives us the directory name where the folder or file is located.
import os # In windows DIR = os.path.dirname("C:\\Users\\xyz\\Documents\\My Web Sites") print(DIR) # In nix* DIR = os.path.dirname("/Documents/MyWebSites") print(DIR)
Running the above code gives us the following result −
C:\Users\xyz\Documents /Documents
Sometimes we may need to check if the complete path given, represents a folder or a file. If the file does not exist then it will give False as the output. If the file exists then the output is True.
print(IS_FILE) IS_FILE = os.path.isfile("C:\\Users\\xyz\\Documents\\My Web Sites\\intro.html") print(IS_FILE) # In nix* IS_FILE = os.path.isfile("/Documents/MyWebSites") print(IS_FILE) IS_FILE = os.path.isfile("/Documents/MyWebSites/music.txt") print(IS_FILE)
Running the above code gives us the following result −
False True False True
This is a interesting function which will normalize the given path by eliminating extra slashes or changing the backslash to forward slash depending on which OS it is. As you can see the output below varies depending on which OS you run the program on.
import os # Windows path NORM_PATH = os.path.normpath("C:/Users/Pradeep/Documents/My Web Sites") print(NORM_PATH) # Unix Path NORM_PATH = os.path.normpath("/home/ubuuser//Documents/") print(NORM_PATH)
Running the above code gives us the following result −
# Running in Windows C:\Users\Pradeep\Documents\My Web Sites \home\ubuuser\Documents # Running in Linux C:/Users/Pradeep/Documents/My Web Sites /home/ubuuser/Documents