How can I test if a directory exists, and create a Path object with one line of code?

104 Views Asked by At

I'm new to using the Python pathlib library, so please edit this question if I'm using incorrect terminology here and there...

I'm using the Path class to both create a directory if it doesn't exist, and then to instantiate a Path object. I currently have this as two lines of code like this because the mkdir method returns NoneType:

my_path = Path("my_dir/my_subdir").mkdir(parents=True, exists_ok=True)
my_path = Path("my_dir/my_subdir")

Is there a way to do this with one line of code? Should I be taking a completely different approach?

2

There are 2 best solutions below

1
On BEST ANSWER

Readability counts. Reducing the number of lines of code should not be a goal in and of itself. Rather, it should be a side effect of simplifications that are beneficial for different reasons (e.g. removing repetition, reducing complexity, emphasizing symmetry, etc.).

I would recommend leaving this as two lines as

my_path = Path("my_dir/my_subdir")
my_path.mkdir(parents=True, exists_ok=True)

But if you really want to write this as one line, you could use either of the following

(my_path := Path("my_dir/my_subdir")).mkdir(parents=True, exists_ok=True)


my_path = Path("my_dir/my_subdir"); my_path.mkdir(parents=True, exists_ok=True)

or you could define a function that ensures that the directory exists when the Path is created:

def path_mkdir(s: str | bytes | os.PathLike) -> Path:
    path = Path(s)
    path.mkdir(parents=True, exist_ok=True)
    return path


my_path = path_mkdir("my_dir/my_subdir")
7
On

Yeah, to create a directory and do Path object instantiation in a single line, you can use the following code:

my_path = Path("my_dir/my_subdir").mkdir(parents=True, exist_ok=True) or Path("my_dir/my_subdir")

In this line, Path("my_dir/my_subdir").mkdir(parents=True, exist_ok=True) is gonna try to create the directory. If the directory already exists, it returns None, but we use the or operator to fall back to Path("my_dir/my_subdir") to instantiate a Path object. I think doing that will allow you to combine both actions into 1 line