![]() |
VOOZH | about |
The os.path.abspath() method in Python's os module is used to get the full (absolute) path of a file or folder. It's useful when you're working with relative paths but need to know the exact location on your system. If you pass a relative path, it converts it to an absolute one and if the path is already absolute, it returns it unchanged. Example:
Output
Explanation: os.path.abspath() convert a relative file path to an absolute path by combining it with the current working directory, then prints the absolute path.
os.path.abspath(path)
Parameter: path is a string representing the relative or absolute path.
Returns: A string representing the absolute path.
Example 1: In this example, we are using the os.path.abspath() function to get the absolute path of the current script file.
Output
Explanation: __file__ attribute represents the script's relative path and os.path.abspath() converts it to the full absolute path by combining it with the current working directory.
Example 2: In this example, we are using the os.path.abspath() function with "." and ".." to get the absolute paths of the current and parent directories.
Output
Explanation: ." refers to the current directory, so os.path.abspath(".") gives its full path. ".." refers to the parent directory and os.path.abspath("..") returns its absolute path.
Example 3: In this example, we are combining a folder and file name using os.path.join() to create a relative path.
Output
Explanation: This code combines the folder "data" and file "report.csv" using os.path.join() to form a relative path. Then, os.path.abspath() converts that relative path into an absolute path, which is stored in variable a.