How to Find the Current Working Directory in Python

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Python provides two different ways to get the current working directory. The first method uses the os module and the second uses pathlib.

Using the os Module to Get the Current Directory

First thing you need to do is to import the module.

>>> import os

Then, you just need call the getcwd function.

>>> import os
>>> os.getcwd()

And that is it! As you can see, the function returns a string. This is not very flexible, what if you want to list all the files in that directory? You will have to call it on os functions again.

The os module is pretty ancient and I wouldn’t recommend using it nowadays. In the following section, I’m going to show you the modern way of getting the current working directory in Python.

Getting the Current Working Directory Through the pathlib Module

The pathlib module was proposed in 2012 and added to Python in the 3.4 version. The idea was to provide an object-oriented API for filesystem paths. This module provides classes that represent the filesystem paths with semantics appropriate for different operating systems. Also, Path objects are immutable and hashable, which helps prevent programming errors caused by mutability.

To get the current working directory using pathlib you can use the classmethod cwd from the Path class. But first, you need to import it.

from pathlib import Path

Them, you can call the method.

>>> from pathlib import Path
>>> Path.cwd()

As you can see, the output is different than the os.getcwd(). As I mentioned earlier, all paths follow the semantics of the underlying filesystem. In my case, I'm using Linux, so the output is a PosixPath. On Windows, cwd returns a WindowsPath.

Being an object allows many cool functionalities such as iterating over all files just by calling a method. However, If you still want to get the string representation, you can call str on the Path.cwd().

>>> str(Path.cwd())

Path.cwd Under the Hood

How does Path know the current directory? The answer is: it calls the os and returns an instance of Path. The following snippet shows the actual implementation.

    def cwd(cls):
        """Return a new path pointing to the current working directory
        (as returned by os.getcwd()).
        return cls(os.getcwd())

Wait! On Linux it returns a PosixPath but the class method belongs to Path. How does it know?

Great question! Path does some magic behind the scenes before creating the object. It implements the __new__ magic method and calls os to determine the underlying operating system. Check the implementation.

        if cls is Path:
            cls = WindowsPath if == 'nt' else PosixPath
        self = cls._from_parts(args, init=False)
        if not self._flavour.is_supported:
            raise NotImplementedError("cannot instantiate %r on your system"
                                      % (cls.__name__,))
        return self


That's it for today, folks! I hope you enjoyed this brief article.

If you liked this post, consider sharing it with your friends or buying me a coffee:)

Other posts you may like:

See you next time!

Comments (1)

Paula Maranhão's photo

Easy peasy! Great for beginners like me.