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 Operators
Node.js vs Python for Backend Development
Python String replace()
Python Deep Learning Cookbook - Indra den Bakker
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program Read a File Line by Line Into a List
Python String isidentifier()
Python max()
Python next()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python format()
Python Program to Add Two Numbers
Python Program to Get the File Name From the File Path
Python Program to Convert Two Lists Into a Dictionary
Python Program to Find the Factorial of a Number
Python String capitalize()
Python Numbers, Type Conversion and Mathematics
Python Program to Check the File Size
Python Program to Find the Square Root
Python String rjust()
Python Dictionary fromkeys()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Count the Number of Each Vowel
Python Program to Check Armstrong Number
Python List insert()
Python Set symmetric_difference()
Python Program to Get Line Count of a File
Python repr()
Python String istitle()
Python Dictionary get()
Python Program to Make a Simple Calculator
Python vars()