How to print full path of current file's directory in Python?


The path of a current file is defined with the help of directory hierarchy; and it contains the backtracked path from the current file to the root directory this file is present in. For instance, consider a file “my_file” belongs to a directory “my_directory”, the path for this file is defined as given below

./my_directory/my_file

The directory, sub-directory and the file are all separated using the “/” separator in the path.

Therefore, to get current file's full path, you can use the os.path.abspath() function. If you want only the directory path, you can call os.path.dirname() method.

Using os.path.abspath() Method

The os.path.abspath() function accepts the path as an argument is used to get the complete normalized absolute path of the current file.

Example

?The following example demonstrates how to retrieve the absolute path of a file by passing its name as an argument to the os.path.abspath() method.

import os
fname = "file1.txt"
print(os.path.abspath(fname))

Output

If we compile and run the program above, the output is given as follows −

/home/cg/root/33992/file1.txt

Using os.path.dirname() Method

The os.path.dirname() function is used to get the directory path (without the file name) of the current file.

This method only accepts a string or a byte as an argument; however, one must pass the complete path of the current file to retrieve the path of its current directory (a part of the path).

This will conclude that −

return value of os.path.dirname() method + file name = return value of os.path.abspath() method

Example

Here, we will first obtain the complete path of the current file using the abspath() method; then the return value is passed as an argument to the dirname() method. The current directory is expected to be retrieved.

import os
fname = "file1.txt"
dn = os.path.abspath(fname)
print(os.path.dirname(dn))

Output

If we compile and run the program above, the output is displayed as follows −

/home/cg/root/78173

Conclusion

The path module provides two functions to get current file's full path. First, use os.path.abspath() function to get the absolute path. Next, use os.path.dirname() function to get only the directory path.

Updated on: 24-Feb-2023

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements