Table of Contents
In this example, you will learn to get the full path of the current working directory.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Using pathlib module
import pathlib
# path of the given file
print(pathlib.Path("my_file.txt").parent.absolute())
# current working directory
print(pathlib.Path().absolute())
Output
/Users/username /Users/username
Using the pathlib module, you can get the current working directory.
- Pass the file’s name in
Path()method. parentgives the logical parent of the path andabsolute()gives the absolute path of the file.pathlib.Path().absolute()gives the current working directory.
2. Example 2: Using os module
import os
# path of the given file
print(os.path.dirname(os.path.abspath("my_file.txt")))
# current working directory
print(os.path.abspath(os.getcwd()))
Output
/Users/username /Users/username
You can do the same thing with the os module.
- Use
abspath()method to get an absolute path. getcwd()gives the current working directory.
Related posts:
Python pow()
Python Program to Multiply Two Matrices
Python Set clear()
Python Dictionary fromkeys()
How to Get Started With Python?
Python Program to Concatenate Two Lists
Python ascii()
Python Global Keyword
Python String rstrip()
Python String isdecimal()
Python String format()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python List index()
Python String isupper()
Python Set copy()
Python String isnumeric()
Python enumerate()
Python Program to Get File Creation and Modification Date
Python List count()
Python String ljust()
Python String translate()
Python String rjust()
Python Set add()
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python object()
Python Program to Find HCF or GCD
Python strptime()
Python Program to Check Armstrong Number
Python Program to Find Armstrong Number in an Interval
Python Closures
Python Program to Find the Largest Among Three Numbers
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho