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

Get Mastering Python for Networking and Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.