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 Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Program to Find ASCII Value of Character
Python Tuple index()
Python Program to Access Index of a List Using for Loop
Python Program to Catch Multiple Exceptions in One Line
Python String title()
Python Program to Display Powers of 2 Using Anonymous Function
Python String zfill()
Python Program to Find Hash of File
Python Program to Randomly Select an Element From the List
Python *args and **kwargs
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python String startswith()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Anonymous / Lambda Function
Python Program to Delete an Element From a Dictionary
Python super()
Python Set isdisjoint()
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Function Arguments
Python String ljust()
Python String swapcase()
Python Dictionary items()
Python List remove()
Python Program to Print the Fibonacci sequence
Python repr()
Python Program to Return Multiple Values From a Function
Python memoryview()
Python Multiple Inheritance
Python String casefold()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Set symmetric_difference_update()