0

My code is something like this:

from pathlib import Path

def make_dir(dirr):
    if Path(dirr).exists() == False:
        Path.mkdir(dirr)
 

make_dir('output')

'output' directory doesn't exist. When I'm trying to create it, I get errors, including AttributeError: 'str' object has no attribute '_closed'. What am I doing wrong?

ferrum
  • 169
  • 1
  • 13

1 Answers1

3

Path is a class, providing methods to call on its instances, not a module full of functions. Path.mkdir(dirr) only works if dirr is already a Path (and even when it works, it's a silly way to spell dirr.mkdir()). Just convert to Path once up front and use the Path instance repeatedly:

def make_dir(dirr):
    dirr = Path(dirr)
    if not dirr.exists():
        dirr.mkdir()

Or more simply, just convert and use mkdir directly with exist_ok (available since Python 3.5) to avoid the need for a test and check before making the directory:

def make_dir(dirr):
    Path(dirr).mkdir(exist_ok=True)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • 1
    Nice and clean. I'd add that `os` module also has a `makedirs` function that can be used with the `exist_ok` argument and enables to create nested directories, if needed. – MatBBastos Jun 01 '21 at 14:59
  • 1
    @MatBBastos: `Path`'s `mkdir` supports creating the parents as well. If they don't want object-oriented paths, then yeah, `os` and `os.path` have you covered, but there are some advantages to using `pathlib` from a code "flow" perspective. I'm particularly a fan of them overloading the `/` operator for path concatenation. :-) – ShadowRanger Jun 01 '21 at 15:02
  • I completely agree, the concatenation is very handy, and `pathlib` does a good job in giving intuitive understanding with the use of `Path`s. I'd also use your solution! My comment was just for the sake of completeness in the subject ;P – MatBBastos Jun 01 '21 at 15:06