The os module contains the path sub-module which provides useful functions for working with and manipulating pathnames.

The normpath() function in the path sub-module is used to normalize a pathname. Normalizing a pathname involves cleaning it up, removing redundant parts such as extra slashes, resolving references to parent directories and symbolic links, etc. This allows paths to be compared and handled consistently, without having to worry about operating system differences.

To use the function, we have to first import it in our program as follows.

from os.path import normpath
normpath(p)

The function returns the normalized path but does not validate whether the resulting path actually exists.

 

from os.path import normpath

path = 'C:/Users/john///Documents/Projects/'

normalized = normpath(path)
print(normalized)

C:\Users\john\Documents\Projects 

In the above example, in the resulting normalized path, forward slashes are replaced with backward slashes because the program is run in a Windows system, the trailing slash is also removed and multiple adjacent slashes replaced with a single slash.