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 dict()
Python Set issuperset()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python String expandtabs()
Python Program to Sort a Dictionary by Value
Python Program to Transpose a Matrix
Python Program to Convert Celsius To Fahrenheit
Python staticmethod()
Debug a JavaMail Program
Python String index()
Python Program to Sort Words in Alphabetic Order
How to Get Started With Python?
Python input()
Python Closures
Python Program to Check if a Key is Already Present in a Dictionary
Python String swapcase()
Python slice()
Python all()
Python Set symmetric_difference()
Python Statement, Indentation and Comments
APIs in Node.js vs Python - A Comparison
Python Dictionary fromkeys()
Python locals()
Python print()
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python RegEx
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python List append()
Python sleep()
Python String format_map()
Python Program to Merge Mails