How to Get a Current Directory in Python?


If you’re new to programming in the Python language, you may be wondering how to get a current directory listing. This is actually a very simple task that can be accomplished in just a few lines of code. In this article, we’ll show you how to do it.

Using the os module

To get the current directory using the os module, use the following code:

import os cwd = os.getcwd() print(cwd) #output: /Users/david/mypython
Code language: Python (python)

This will print the current working directory to the screen.

Using the pathlib module

To get the current directory using the pathlib module, use the following code:

from pathlib import Path cwd = Path.cwd() print(cwd) #output: /Users/david/mypython
Code language: Python (python)

This will also print the current working directory to the screen. As you can see, both methods are very similar. The pathlib module is newer than the os module, so if you’re using Python 3.4 or newer, it’s generally recommended to use pathlib instead of os.

Other Ways to Get the Current Directory in Python

Although the os.getcwd() function is the easiest way to get the current directory, there are a few other ways to accomplish this as well.

Here is an example of how this would work:

import os current_path = os.path.realpath('.') print(current_path)
Code language: JavaScript (javascript)

Conclusion:

There are a few different ways that you can get your current working directory in Python. The most straightforward way is to use the built-in os module and its getcwd() function. However, you can also use other methods such as using the chdir() function in conjunction with Python’s file variable. No matter which method you choose, getting your current directory in Python is a simple task!

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts