One of the foremost important aspects of programming you want to understand is your project directory. It gives you a far better grasp of your files and allows you to relate with them more easily. Specially, when you have to or need to perform actions like file linking, module import. Also, directory switching and far more actions. It is a necessary aspect when executing Python projects also . Thus, in this post, I will be talking about how to get current directory python.

Introduction

Till now, what have we seen mostly. We mostly have seen the various complex computational capabilities of Python. But today, we will see how we can use it to handle Python directory. After this tutorial, one can create, rename, list files in a directory in Python.

So, let’s highlight the techniques you’ll have to use to access your current Python directory, and, also take a look over various possible tweaks one can apply thereto generally.

Dealing with Directories — Get current directory Python

The methods that is used to deal with the Python directory are in the in-built ‘os’ module. This ‘os’ module is the same in all operating systems. Thus, it means you would like to import that module before you’ll start executing commands that affect your working directory.

However, a bit like the other Python blocks of code, these commands are written on a Python shell. Or, for that matter, a Python file if you’re using other code editors. It is because the various ‘os’ operations are Python packages, which cannot be executed directly from cmd.

Get current directory Python

Get the present Python Working Directory

You can get your current Python folder by using either the ‘os.path’/’os.getcwd’ method. The ‘os.getcwd’ operation just checks your current working directory, but, the ‘os.path’ operation checks both the present directory and also the base path of your working directory.

Lets take its application as a code :

import os
base = os.path.dirname(os.path.dirname(os.path.abspath("file path")))
print(base)

Lets now get the current working directory.

import os
current = os.path.dirname(os.path.realpath("file path"))
print(current)

Now, lets look at the ‘os.getcwd’ method — Get current directory Python

### To get the current working directory

import os
current = os.getcwd()
print(current)


### To change the present working directory

import os
change_dir = os.chdir('C:/Users/Shubham/Desktop/Python Projects')
current = os.getcwd()
print(current)

Why do we change Python Directory?

One can change the present Python directory to inherit another file path if you wish. To do that, one simply needs to define the file path for the new working directory as written above.

The code written above changes the present working directory to the one in the brackets. The output of the code above is return in the current variable.

Various Operations to be performed while handling Python Directories

Not only working with the present folder, one can perform various other operations on Python directories.

These various operations can be performed after importing the ‘os’ module. Lets look at the various commands.

/*   list out all the files and sub-folders within the present Python working directory  */
files = os.listdir()


/*   make a replacement Python directory within the present project directory  */
os.mkdir('directory_name')


/*   rename any named file or folder within the present directory by supplying its original name, followed by its new name    */
os.rename('old_directory_name', 'new_directory_name')


/*   remove empty folder within the present working path    */
os.rmdir('directory_name')


/*   delete a file from the Python directory    */
os.remove('name_of_file')


/*    delete a non-empty folder from the working directory, to use this command, import the shutil library by typing import shutil in your working file or Python shell   */
shutil.rmtree('directory_name')

Handling the errors while changing the directory

Now, that we have gone through the various operations. We should also be aware. Of the ways and methods to handle the various exceptions that might come your way.

###  First we need to import all necessary libraries
import sys, os 
	
###  Current Directory 
current = os.getcwd() 
	
###  Some non-existing directory 
false_loc = 'false_dir/temp'
	
###  When inserting into false directory 
try: 
	print("Inserting into -", os.getcwd()) 
	os.chdir(false_loc) 
		
###  Catching the exception	 
except: 
	print(" There is some error in the specific directory ")  
	print(sys.exc_info()) 
			
###  Working around with finally		 
finally: 
	print() 
	print("Finally Restoring the path") 
	os.chdir(current) 
	print("Current Directory is : ", os.getcwd()) 

===> SUMMING UP — Get current directory Python ……

Thus, through this article, I have tried to explain to you how to get current working directory in Python. Also, thereby, providing you with the knowledge about various operations to perform on your directory. We have thus, seen the many functionalities of the ‘os’ library.

Get current directory Python

By and through this article, thus, I suppose I have made myself pretty clear. But, in case, you still have some doubts lingering. Then, please do write to me in the comments section and I am as always, ever-ready to help you. And, also solve your many queries and problems.

Until then bidding you Good-Bye !!! Ok, wait ….. before you go, you may check out my various other posts. Also, for the simple reason, that is, to enhance your knowledge on various other topics of importance. Where ??? Here……

Categorized in: