Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

path
current file
directory
communitycreator

How to get full path of the current file directory using Python

Fouzia Bashir

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


# Signature
os.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.

main.py
data.csv
edpresso.txt
# importing operating system module in program
import os
# File names
file_name1 = 'edpresso.txt'
file_name2 = 'data.csv'
# Print absolute path name of argument file
# edpresso.txt
print(f"File path of {file_name1}: {os.path.abspath(file_name1)}")
# data.csv
print(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.

RELATED TAGS

path
current file
directory
communitycreator
RELATED COURSES

View all Courses

Keep Exploring