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
1 2 3 4 5 6 7 | import pathlib # path of the given file print (pathlib.Path( "my_file.txt" ).parent.absolute()) # current working directory print (pathlib.Path().absolute()) |
Output
1 2 | / 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
1 2 3 4 5 6 7 | 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
1 2 | / 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 String center()
Python String casefold()
Python setattr()
Deep Learning with Python - Francois Chollet
Python Package
Python String find()
Python Dictionary copy()
Python Set intersection_update()
Python List extend()
Python pass statement
Python staticmethod()
Python all()
Python Program to Get File Creation and Modification Date
Python String strip()
Python sum()
Python hasattr()
Python List index()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Program to Find the Factors of a Number
Python Program to Multiply Two Matrices
Python Program to Find ASCII Value of Character
Python Program to Add Two Matrices
Python Program to Print Colored Text to the Terminal
Python Namespace and Scope
Python Program to Illustrate Different Set Operations
Python Dictionary get()
Python Set symmetric_difference()
Python Dictionary values()
Python Get Current time
Python String startswith()
Python Program Read a File Line by Line Into a List
Python Program to Display the multiplication Table