- Mastering Python for Networking and Security
- José Manuel Ortega
- 107字
- 2025-04-04 16:14:24
Creating directories in Python
You can create your own directory using the os.makedirs() function:
>>> if not os.path.exists('my_dir'):
>>> os.makedirs('my_dir')
This code checks whether the my_dir directory exists; if it does not exist, it will call os.makedirs ('my_dir') to create the directory.
If you create the directory after verifying that the directory does not exist, before your call to os.makedirs ('my_dir') is executed, you may generate an error or an exception.
If you want to be extra careful and catch any potential exceptions, you can wrap your call to os.makedirs('my_dir') in a try...except block:
if not os.path.exists('my_dir'):
try:
os.makedirs('my_dir')
except OSError as e:
print e