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?
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")