[파이썬] os 절대 경로 반환: `os.path.abspath()`

To use os.path.abspath(), you need to import the os module first. Here’s an example:

import os

relative_path = "my_folder/my_file.txt"
absolute_path = os.path.abspath(relative_path)

print(f"Relative path: {relative_path}")
print(f"Absolute path: {absolute_path}")

Output:

Relative path: my_folder/my_file.txt
Absolute path: /home/user/my_folder/my_file.txt

In the example above, we start by defining a relative path (my_folder/my_file.txt). This is a path that is relative to the current working directory.

We then pass this relative path to os.path.abspath() and assign the return value to the variable absolute_path. The os.path.abspath() function converts the relative path to an absolute path based on the current working directory.

Finally, we print both the relative and absolute paths using the print() function.

The output shows that the relative path my_folder/my_file.txt is converted to the absolute path /home/user/my_folder/my_file.txt. The absolute path represents the full path from the root directory to the specified file or directory.

Using os.path.abspath() can be beneficial when you want to convert a relative path to an absolute path, especially when dealing with files, directories, or file operations in your Python programs.