Better ways to create a directory in python
When you're creating a new directory in python, it's better to check if that directory exists first, in case your code run into error.
Example 1
- use
os.path.exists()
to check if the directory's existence - then create a directory with
os.mkdir()
only if it does not exist
import os
path_to_dir = '/content/test'
if not os.path.exists(path_to_dir):
os.mkdir(path_to_dir)
Example 2
- use a try-except block to handle error
import os
path_to_dir = '/content/test'
try:
os.mkdir(path_to_dir )
except OSError as error:
print(error)
Example 3
- use
os.mkdirs()
when there is any non-existent directory in your path - for instance, you want to create a directory in called
/test2
in directory/test1
, however directory/test1
is missing.
import os
path_to_dir = '/content/test1/test2/'
try:
os.mkdir(path_to_dir )
except OSError as error:
print(error)