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 List sort()
Python Dictionary clear()
Node.js vs Python for Backend Development
Python Tuple count()
Python compile()
Python slice()
Python delattr()
Python Program to Check Prime Number
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Multiply Two Matrices
Python Data Structures and Algorithms - Benjamin Baka
Python Program to Check if a Key is Already Present in a Dictionary
Python list()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python getattr()
Python Numbers, Type Conversion and Mathematics
Python Program to Split a List Into Evenly Sized Chunks
Python Program to Get a Substring of a String
Python Set symmetric_difference_update()
Python Set difference()
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Set intersection()
Python help()
Python String translate()
Python exec()
Python Input, Output and Import
Python object()
Python Matrices and NumPy Arrays
Python Type Conversion and Type Casting
Python Operator Overloading
Python range()
Python Set union()