0

I have the following code snippet

outdir = os.path.join(os.getcwd(), "new-recipes", "test")
            
print("Output to:", outdir)
print(" ") 

# If directory doesn't exist, make it 
if not os.path.isdir(outdir):
    os.mkdir(outdir) 
os.chdir(outdir) 

when I run it on a Windows machine I get the output

Output to: C:\Users\wbehrens\Desktop\Code\conan-3pc\new-recipes\test

[WinError 3] The system cannot find the path specified: 'C:\\Users\\wbehrens\\Desktop\\Code\\conan-3pc\\new-recipes\\test'

I added an absolute path because I found somewhere that it works better but I still get no luck.

WilliamB
  • 65
  • 5
  • Probably one of the ancestor directories doesn't exist (`new-recipes` for example). – CherryDT Jun 22 '22 at 20:23
  • @CherryDT you're right, is there something akin to a mkdir -p? – WilliamB Jun 22 '22 at 20:23
  • You can use `os.makedirs(outdir, exist_ok=True)` to get `mkdir -p`-like behavior. See [this question](https://stackoverflow.com/questions/6004073/how-can-i-create-directories-recursively). – CherryDT Jun 22 '22 at 20:24

2 Answers2

1

I think a more efficient workaround is using the pathlib library, which is a little easier to work with when creating paths. This should accomplish what you are looking for:

from pathlib import Path

outdir = Path.cwd() / "new-recipes" / "test"
if Path.exists(outdir) == True:
    print("Directory already exists!")
else:
    outdir.mkdir(parents=True, exist_ok=True)
    print("Directory created!")

The syntax of pathlib's path function is where Path.exists(outdir) returns either True or False. This in turn allows the if statement that follows to utilize the output for its logic. For outdir.mkdir(parents=True, exist_ok=True), parents=True means that any missing parents of this path are created as needed for the directory. exist_ok=True means that no action will be taken to create the directory if the path already exists.

Hope this helps!

CherryDT
  • 25,571
  • 5
  • 49
  • 74
Lnb2628
  • 26
  • 1
-1

Try this instead

outdir = "/test"  # or absolute path, which ever you want

# Try making a directory
try:
    os.makedirs(outdir)
except OSError as e:
    print("Directory already exists!")
MrAvatin
  • 21
  • 4
  • This won't solve the problem. Instead, it will falsely print `Directory already exists!` when in fact a parent directory is missing. – CherryDT Jun 22 '22 at 20:27
  • You should have mentioned in your question that you wanted to make the parent directory too. In that case replace mkdir with makedirs. – MrAvatin Jun 22 '22 at 20:35