Python os.path.normpath() Method

  1. Syntax of the os.path.normpath() Method
  2. Example 1: Working With the os.path.normpath() Method in Python
  3. Example 2: Use the os.path.normpath() Method on Windows OS
  4. Example 3: Two First Slashes // in the os.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.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python OS

  • Python os.access() Method
  • Python os.chdir() Method
  • Python os.closerange() Method
  • Python os.path.getsize() Method