How to get full path of the current file directory using Python
Introduction
The OS module in Python provides an interface to interact with operating system commands. The os.path is a submodule of the operating system module that contains functionality about pathnames.
If you want to get the current file directory or pathname Python provides os.path.abspath(). It returns a normalized version of the pathname. The normpath() function also provides the same functionality and returns pathname as well.
Syntax
# Signatureos.path.abspath(path)
Parameters
It takes the following argument:
path: A path-like instance representing a local file system path.
Return value
It returns a normalized and absolutized pathname.
Explanation
In this code snippet, we will write a program to fetch file pathname. We will use os.path.abspath() function of os.path submodule, to fetch pathname from the local filesystem.
# importing operating system module in programimport os# File namesfile_name1 = 'edpresso.txt'file_name2 = 'data.csv'# Print absolute path name of argument file# edpresso.txtprint(f"File path of {file_name1}: {os.path.abspath(file_name1)}")# data.csvprint(f"File path of {file_name2}: {os.path.abspath(file_name2)}")
Line 4–5: We create two variables. Each contains a string of file name with extension.
Line 8: We call
os.path.abspath()to get'edpresso.txt'pathname.Line 10: We call
os.path.abspath()to get'data.csv'pathname.