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. parent
gives 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 Data Structures and Algorithms - Benjamin Baka
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python List index()
Python map()
Python Program to Merge Mails
Python Dictionary copy()
Python Program to Find the Size (Resolution) of a Image
Python super()
Python Program to Differentiate Between type() and isinstance()
Python Set issuperset()
Python Program to Print Colored Text to the Terminal
Python Get Current time
Python Set issubset()
Python dict()
Python frozenset()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Program to Compute the Power of a Number
Python Set pop()
Python Program to Find Numbers Divisible by Another Number
Python Set intersection()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python filter()
Python File I/O Operation
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python String strip()
Python Set remove()
Python List reverse()
Python Program to Calculate the Area of a Triangle
Python enumerate()
Python Program to Print the Fibonacci sequence
Python Program to Find Hash of File
Python Program to Find the Largest Among Three Numbers