Python os.path.normcase() Method



The normcase(path) method in the os.path module is used to normalize the case of a pathname. It converts all characters in the pathname to lowercase and also converts forward slashes to backward slashes. This method is especially useful on Windows operating systems. On other operating systems like Unix-based systems, the method returns the path unchanged.

When you working with file paths this method ensures consistency in path representations, making it easier to work with file paths on Windows operating systems.

Syntax

Following is the syntax of the method −

os.path.normcase(path)

Parameters

Here are the details of its parameters −

  • path: This parameter represents a path-like object, which can be either a string or bytes object representing a file system path, or an object implementing the 'os.PathLike' protocol.

Return Value

The method returns a string representing the normalized case of the provided path.

Examples

Let's explore some examples to understand how the os.path.normcase() method works.

Example

The following example uses the os.path.normcase() method to get the normalized case of the input pathname 'D:/MyFile.txt'.

# Import the os module
import os 

# Normalizing a path
path = 'D:/MyFile.txt'
normalized_path = os.path.normcase(path)

# Print the results 
print('The resultant normalized path:',normalized_path)

Output

On executing the above code you will get the following output −

The resultant normalized path: d:\myfile.txt
If you execute the above program in the other operating systems you will get the below output(unchanged path name).
The resultant normalized path: D:/MyFile.txt

Example

In this example, the following pathname 'A//B/C/./../D' in given to the os.path.normcase() method, which is then converts the forward slashes to backward slashes.

# Import the os module
import os 

# Normalizing a path
path = 'A//B/C/./../D'
normalized_path = os.path.normcase(path)

# Print the results 
print('The resultant normalized case pathname is:',normalized_path)

Output

On executing the above code in our online compiler will get the following output −

The resultant normalized case pathname is: a\\b\c\.\..\d

Example

Here is the another example that demonestrates the working of the os.path.normcase() method on Windows platform.

# Import the os module
import os 

# Normalizing a path
path = 'MyDir/.//../MyFile.txt'
normalized_path = os.path.normcase(path)

# Print the results 
print('The resultant normalized case pathname is:',normalized_path)

Output

On executing the above code in our online compiler will get the following output −

The resultant normalized case pathname is: mydir\.\\..\myfile.txt
os_path_methods.htm
Advertisements