[파이썬] os 경로 정규화: `os.path.normpath()`

In Python, the os.path module provides various functions for working with file paths. One such useful function is os.path.normpath(), which helps in normalizing and simplifying the given file path.

What is path normalization?

Path normalization is the process of transforming a given file path into a standardized and consistent format. This is particularly important when dealing with file paths that may contain various extra elements like redundant separators, relative paths, or special characters.

The os.path.normpath() function

The os.path.normpath() function in Python takes a file path as input and returns the normalized path as output. It performs the following operations to normalize the given path:

  1. Removes any redundant separators or dots (.) from the path.
  2. Resolves any relative paths (..) and makes the path absolute.
  3. Replaces backslashes (\) with forward slashes (/) for cross-platform compatibility.

Example usage

Let’s consider a few examples to understand how os.path.normpath() works:

import os

path1 = "/usr/local/../bin"
normalized_path1 = os.path.normpath(path1)
print(normalized_path1)  # Output: "/usr/bin"

path2 = "C:\\Program Files\\.\\Python\\..\\Scripts"
normalized_path2 = os.path.normpath(path2)
print(normalized_path2)  # Output: "C:/Program Files/Scripts"

In the first example, the initial path "/usr/local/../bin" contains a redundant “../”. The os.path.normpath() function removes this and returns the normalized path "/usr/bin".

The second example demonstrates path normalization on Windows. The initial path "C:\\Program Files\\.\\Python\\..\\Scripts" contains a redundant “.\” and “..”. The function os.path.normpath() removes these and replaces the backslashes with forward slashes, resulting in the normalized path "C:/Program Files/Scripts".

Benefits of using os.path.normpath()

Conclusion

When working with file paths in Python, using the os.path.normpath() function can ensure that your paths are normalized, standardized, and consistent. It helps eliminate any potential issues that may arise due to variations in file path formats across different operating systems, making your code more robust and portable.