Current Working Directory in Python

Current Working Directory in Python
(Last Updated On: 17/05/2023)

Python Program to Get Current Working Directory Using pathlib

# Python Program to Get Current Working Directory Using pathlib
 
# importing pathlib module
import pathlib

# path of the given file
print(pathlib.Path("file1.txt").parent.absolute())

# current working directory
print(pathlib.Path().absolute())

Output:

/Users/username
/Users/username

Python Program to Get Current Working Directory Using OS

# Python Program to Get Current Working Directory Using OS

#importing os module
import os

# path of the given file
print(os.path.dirname(os.path.abspath("file_one.txt")))

# current working directory
print(os.path.abspath(os.getcwd()))

Output:

/Users/username
/Users/username

Leave a Reply

Your email address will not be published. Required fields are marked *