[파이썬] os 절대 경로 확인: `os.path.isabs()`

In Python, the os.path module provides various methods for manipulating paths. One commonly used method is isabs(), which allows you to check whether a given path is an absolute path.

An absolute path is a complete path that specifies the exact location of a file or directory in the filesystem, starting from the root directory. On the other hand, a relative path specifies the location of a file or directory relative to the current working directory.

The isabs() method takes a path as input and returns True if it is an absolute path, and False otherwise.

Here’s an example usage of os.path.isabs():

import os

path1 = '/usr/local/bin/python'
path2 = 'scripts/myscript.py'
path3 = '../documents/report.docx'

print(os.path.isabs(path1))  # True
print(os.path.isabs(path2))  # False
print(os.path.isabs(path3))  # False

In the above example, path1 is an absolute path starting from the root directory (/), while path2 and path3 are relative paths.

The output of the code will be:

True
False
False

By using os.path.isabs(), you can easily determine whether a given path is an absolute path or not. This can be particularly useful when dealing with file handling, path manipulation, or writing platform-independent code.

Remember to handle exceptions appropriately when working with paths to ensure your code handles unexpected scenarios gracefully.