Working With The Current Directory In Python

In this tutorial, you will learn about working with the current directory in Python.

Basically, in Python, you do most of the directory-related stuff using the OS library present in it. This module makes it easy to use features that depend on the operating system of any computer. In order to read or write a file, see open(). If you want to change the path, see os.path.

Let us see in the details all the problems you can face when working with Directory in Python.

How To Get Current Working Directory In Python

Get Current Working Directory

You can use the OS library to get the current directory name in Python. Let us see in the below example code.

#importing OS library
import os

#getting the current Directory Path
currentDir = os.getcwd()

#Printing The Current Directory Name
print(currentDir)

Output:

Path of the Current Terminal Location.
C:\Users\ravi9\Coduber

As you can see using OS function getcwd I was able to get the current directory where this Python file is present and being executed.

Get Current Working Directory With Filename

Alternatively, if you want to get the current working directory with the current working file then you can use the below code. You can achieve it using the __file__ method in Python[1]. As a rule, this is the pathname of a file that was used to load this module, so this is the name of that file.

#importing OS library
import os

#getting the current Directory Path
currentDirWithFile = __file__

#Printing The Current Directory Name
print("Path of the Current Terminal Location.")
print(currentDirWithFile)

Output:

Path of the Current Terminal Location.
c:\Users\Coduber\test.py

You can see the output of the above code is the location of the current directory with the filename. Or you can also use the below code and method mentioned in this code as an example to print and get the path of the current directory and filename.

#importing OS library
import os

#Printing The Current Directory Name
print("Path of the Current Terminal Location.")
print(__file__)

#Printing the Full Path including the Filename
getFullPath = os.path.realpath(__file__)
print(getFullPath)

#Printing the Path and Filename separately 
getPath, getFilename = os.path.split(getFullPath)
print(getPath)
print(getFilename)

#Priting Only Dirname
getOnlyDirName = os.path.dirname()
print(getOnlyDirName)

Output:

Path of the Current Terminal Location.
c:\Users\Coduber\test.py
C:\Users\Coduber\test.py
C:\Users\Coduber
test.py
C:\Users\Coduber

As you can see in the above code, I have used the function os.path.realpath(), split(), dirname(), to get the current directory path and the current filename.

Using the Pathlib Libray To get Current Working Directory

There is another library in Python as well called Pathlib that can also be used to get the current directory information. This library was created to make path-related experiences more refined. Let us see in the below example code the usage of Pathlib and cwd to get the current directory information.

#Importing the Path from Pathlib
from pathlib import Path

#Printing Current Directory path
print(Path.cwd())

Output:

C:\Users\Coduber\

If you want to get the absolute path of the file then you can use the __file__ with Pathlib and then using the resolve function it will print the absolute path of the file. Let us see in the below example code.

#Importing the Path from Pathlib
from pathlib import Path

#Printing Current Directory path
print(Path(__file__).resolve())

Output:

C:\Users\Coduber\test.py

Get the Absolute Path of Current Directory using Pathlib

If you want to get the parent directory of the current file and want to be absolutely sure about the path then all you are required to do is add the “.parent” line in the last of the resolve function. Let us see in the below example code.

#Importing the Path from Pathlib
from pathlib import Path

#Printing Current Directory path
print(Path(__file__).resolve().parent)

Output:

C:\Users\Coduber

Python Get Current Files in Directory

If you want to get all the files in the directory specified in the preceding code, i.e. using the OS library function getcwd (). Let us examine the example code below to see how to retrieve the directory’s current files.

#Importing the OS
import os

#Printing Current Directory Files path
print(os.listdir('.'))

Output:

['.vscode', 'newCSV.csv', 'student.csv', 'test.cpp', 'test.exe', 'Test.html', 'test.py', 'test2.js', 'Test4.js']

As you can see using the listdir function from the OS library I was able to get current files in the directory using Python in form of a list.

Check If The Directory Is Empty Python

If you want to check if the directory is empty then you can use the listdir() function from the OS library in Python.

This function returns the number of files and folders inside the input path. If there are no folders or files then it will return an empty list and you can then check the length of the returned list from the listdir() function.

If the length is zero then it means that the folder is empty. Let us see in the below example code how to check if the directory is empty in Python.

#Importing the OS Library  
import os
  
# path of the directory To Check If Empty
inputPath = "C:/Users/Coduber/"
  
# Getting the list of files and Folders
getFilesFolder = os.listdir(inputPath)
  
# Checking if the return list is empty or not
if len(getFilesFolder) == 0:
    print("The Input directory is Empty.")
else:
    print("The Input Directory is Not Empty.")

Output:

The Input Directory is Empty.

Wrap Up

I hope you were able to resolve the common issue that arises when working with the current directory in Python. I’ve listed numerous methods for obtaining the current directory path and filename.

Kindly notify me in the comment area below if you believe you know of a more efficient way than the one presented above. I will gladly include it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. Remove All Occurrences Of A Character In A String
  2. How To Convert GIF To Lottie JSON
  3. How To Get Every nth Element From A List in Python
  4. How To Run Python Script Constantly In Background
  5. How To Convert Python String To Array
  6. Code Example: How To Check If Set Is Empty In Python
  7. Code Examples – Write A List To CSV Using Python