# How to Find the Current Working Directory in Python

Python provides two different ways to get the current working directory. The first method uses the `os` module and the second uses [the newer `pathlib`](https://miguendes.me/python-pathlib).

## Using the `os` Module to Get the Current Directory

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

```python
>>> import os
```

Then, you just need call the `getcwd` function.

```python
>>> import os
...
>>> os.getcwd()
'/home/miguel'
```

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.

```python
from pathlib import Path
```

Them, you can call the method.

```python
>>> from pathlib import Path
...
>>> Path.cwd()
PosixPath('/home/miguel')
```
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()`.

```python
>>> str(Path.cwd())
'/home/miguel'
```

### `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.

```python
    @classmethod
    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.

```python
    def __new__(cls, *args, **kwargs):
        if cls is Path:
            cls = WindowsPath if os.name == '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__,))
        self._init()
        return self
```

## Conclusion

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

Other posts you may like:
- [Python pathlib Cookbook: 57+ Examples to Master It (2021)](https://miguendes.me/python-pathlib)

- [3 Ways to Test API Client Applications in Python](https://miguendes.me/3-ways-to-test-api-client-applications-in-python)

- [5 Hidden Python Features You Probably Never Heard Of](https://miguendes.me/5-hidden-python-features-you-probably-never-heard-of)

- [7 pytest Features and Plugins That Will Save You Tons of Time](https://miguendes.me/7-pytest-features-and-plugins-that-will-save-you-tons-of-time)

- [Everything You Need to Know About Python's Namedtuples](https://miguendes.me/everything-you-need-to-know-about-pythons-namedtuples)

See you next time!

This post was originally published at [https://miguendes.me](https://miguendes.me/how-to-find-the-current-working-directory-in-python)
