Python os.path.normpath() Method
-
Syntax of the
os.path.normpath()
Method -
Example 1: Working With the
os.path.normpath()
Method in Python -
Example 2: Use the
os.path.normpath()
Method on Windows OS -
Example 3: Two First Slashes
//
in theos.path.normpath()
Method in Python

Python os.path.normpath()
method is the most efficient way of normalizing a specified path. Path normalization includes collapsing all redundant separators, such as backslash, period, and up-level references in a path address.
Syntax of the os.path.normpath()
Method
os.path.normpath(path)
Parameters
path |
It is an address object of a file system path or a symlink. The object can either be a string or bytes. |
Return
The return type of this method is a string value. A path string containing the normalized address of a file is returned.
Example 1: Working With the os.path.normpath()
Method in Python
import os
path = '/home///user/Documents'
normalize = os.path.normpath(path)
print(normalize)
path = '/home/./Documents'
normalize = os.path.normpath(path)
print(normalize)
path = '/home/user/temp/../Documents'
normalize = os.path.normpath(path)
print(normalize)
Output:
/home/user/Documents
/home/Documents
/home/user/Documents
The os.path.normpath()
converts A//B
, A/B/
, A/./B
and A/home/../B
all to A/B
.
Example 2: Use the os.path.normpath()
Method on Windows OS
import os
path = r'C:/Users'
normalize = os.path.normpath(path)
print(normalize)
path = r'C:\Users\.\Documents'
normalize = os.path.normpath(path)
print(normalize)
path = r'C:\Users\admin\temp\..\Documents'
normalize = os.path.normpath(path)
print(normalize)
Output:
C:\Users
C:\Users\.\Documents
C:\Users\admin\temp\..\Documents
On Windows, this method converts forward slashes to backward slashes.
Example 3: Two First Slashes //
in the os.path.normpath()
Method in Python
import os
directory=os.path.normpath('//user//Home/')
print(directory)
Output:
//user/Home
The os.path.normpath()
eliminates all the double slashes, but in this case, it doesn’t remove them because on Windows, there is a path ambiguity that Python preserves.
//user
and /user
are fundamentally different paths, so if Python removes the double front slash, it can unknowingly change the directory.
Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.
LinkedIn