DEV Community

Discussion on: How to get the current directory in python?

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