DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Updated on • Originally published at flexiple.com

How to get the current directory in python?

In this python tutorial, we look at how you can get the current working directory in Python and how you can change the working directory.

This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts. However, in case you are here only for the solution use this link.

Table of Content

What are directories and how do they work?

In case you are new to programming, directories are nothing but folders. These directories are present inside a root folder eg: C: \ or D: \ and each directory could contain files or subdirectories and so on. And to retrieve a file from you would need to know the exact path to reach the file, in windows you can view a particular file path by right-clicking the file-General-Location.

Furthermore, when you run a python script, the current directory is set to the location of the script. And, while trying to run another script or while handling files in python the Current Working Directory (CWD) is important as python would not be able to access the files if there aren't in the CWD. It is in these scenarios that the python get current directory helps you know which directory you are in currently.

Python get current directory

The python get current directory would help you know which directory you are currently in, to do this we use the OS module to interact with the operating system and we use the os.getcwd() method to return the path of the current directory.

Syntax of os.getcwd:

os.getcwd()
Enter fullscreen mode Exit fullscreen mode

Code for python get current directory:

#importing the os module
import os

#to get the current working directory
directory = os.getcwd()

print(directory)
Enter fullscreen mode Exit fullscreen mode

The output way may vary depending on the directory you are in but it would root folder eg: D: \ and the directory prefixed by a \.

Python change directory

Similar to python get current directory we use the os module to change the current directory as well. We make use of the chdir() methods to change the directory. Uses of this would again be to change the current directory in order to retrieve relevant files.

Syntax of chdir():

os.chdir(path)
Enter fullscreen mode Exit fullscreen mode

Parameters:

path - The path to the new directory

Code to change current directory:

Let's say i wanted to change the directory to a directory called "freelancer" inside the "flexiple"

import os

os.chdir("C:\freelancer\flexiple")
Enter fullscreen mode Exit fullscreen mode

Limitations and Caveats

  • The python get current directory method only return the current working directory, in case you want the entire path, use os.path.realpath(file)
  • Unlike the python get current directory the change directory requires a parameter that needs to be a directory, and if not python return a NotADirectoryError
  • If the directory does not exist then a FileNotFoundError is returned. And in case the user lacks the necessary permissions to access the directory a 1PermissionError is returned.

Do let me know your thoughts in the comment section below. Happy coding :)

Top comments (1)

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

The os module is discouraged in modern Python for working with paths. You should almost always be using pathlib instead.

Here's an example. I'm on Linux, so a PosixPath is created. On Windows, a WindowsPath would be created instead:

from pathlib import Path
my_dir = Path.cwd()
print(my_dir)  # prints "/home/jason/code_examples"
repr(my_dir)  # prints "PosixPath('/home/jason/code_examples')"
Enter fullscreen mode Exit fullscreen mode

You can combine paths with the / operator, and work with them directly, like this:

my_file = my_dir / 'new_dir' / 'file_thing'
print(my_file)  # prints "/home/jason//code_examples/new_dir/file_thing"

my_file.parent.mkdir(exist_ok=True, parents=True)  # create the parent directory
my_file.touch()  # creates empty file 'file_thing' at path

other_file = my_file.parent / 'other_file'
with other_file.open('w') as file:
    file.write("Hello, world!\n")

with other_file.open('r') as file:
    print(file.read().strip())  # prints "Hello, world!"
Enter fullscreen mode Exit fullscreen mode

The exact same code will work on Windows and macOS without modification. Everything you can do with files in os, you can do more easily with pathlib.

Here's the pathlib documentation: docs.python.org/3/library/pathlib....