The os.path is a built-in Python module that provides a range of useful functions to change files and directories. These methods are used for various purposes, such as merging, normalizing, and retrieving path names. The path parameters are either strings or bytes.
Python’s native os.listdir() and os.path functions are pretty low-level. Iterating through a directory requires your program to congregate file paths manually. Let’s deep dive into os library and see its path.abspath() function.
Python os.path.abspath
The os.path.abspath() is a built-in Python function that returns a normalized absolute version of the pathname, which means the abspath() function returns the pathname to a path passed as a parameter.
Syntax
os.path.abspath(path)
Parameters
The os.path.abspath() takes a path or file name as a parameter representing a file system path.
Return Value
The abspath() method returns a normalized version of the pathname path.
Example
To work with path functions, import os module. Then define a path or filename and pass that to the abspath() function, and it returns the normalized path.
import os path = "Netflix.csv" file_name = os.path.abspath(path) print(file_name)
Output
/Users/krunal/Desktop/code/pyt/database/Netflix.csv
As you can see from the output, I have passed a filename from my current directory, which is a database, and it returns an absolute path to that directory and then the filename.
After changing the current directory
To change the current directory in Python, use the os.chdir() method.
import os path = "Pro.R" os.chdir("/Users/krunal/Desktop/code/R") file_name = os.path.abspath(path) print(file_name)
Output
/Users/krunal/Desktop/code/R/Pro.R
The os.path.abspath() function removes things like . and .. from the path giving a full path from the root of the directory tree to the named file (or symlink).
That is it for os.path.abspath() function in Python.