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.
CodePudding user response:
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!
CodePudding user response:
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!")