I want to check if there exist a folder in the current folder my code is in, how can this be done?
What I mean is, we have folder called code_folder, which has the python code, i want to check in this python code if in this code_folder we have another folder called folder_1, if is it exists we can store something in it, if not we creat the folder and store something in it.
CodePudding user response:
try this code
import os
path = "code_folder"
# Check whether the defined path exists or not
if not os.path.exists(path):
# Create a new directory
os.makedirs(path)
print("The new directory is created!")
else:
pass
CodePudding user response:
You can use pathlib
for this.
if pathlib.Path("path/to/code_folder/folder_1").isdir():
print("the directory exists")
But really, you don't need to check anything, you can just use the exists_ok
argument of Path.mkdir
, so just:
pathlib.Path("path/to/code_folder/foler_1").mkdir(exists_ok=True)