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 Program to Create a Countdown Timer
Python Program to Illustrate Different Set Operations
Python Program to Remove Punctuations From a String
Python String isidentifier()
Python Data Structures and Algorithms - Benjamin Baka
Python exec()
Python Program to Check Armstrong Number
Python Program to Find Sum of Natural Numbers Using Recursion
Python Dictionary values()
Python String translate()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Program to Convert Kilometers to Miles
Python Matrices and NumPy Arrays
Python Program to Safely Create a Nested Directory
Python Program to Sort a Dictionary by Value
Python tuple()
Python id()
Python isinstance()
Python timestamp to datetime and vice-versa
Python Program to Calculate the Area of a Triangle
Python Program to Differentiate Between del, remove, and pop on a List
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Program to Convert Decimal to Binary Using Recursion
Python Function Arguments
Python String format_map()
Python Program to Find Hash of File
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Objects and Classes
Python reversed()
Python Program to Delete an Element From a Dictionary
Python Program to Merge Mails