Skip to Content
Mastering Python for Networking and Security
book

Mastering Python for Networking and Security

by José Manuel Ortega
September 2018
Intermediate to advanced
426 pages
10h 46m
English
Packt Publishing
Content preview from Mastering Python for Networking and Security

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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Python for Networking and Security - Second Edition

Mastering Python for Networking and Security - Second Edition

José Manuel Ortega
Python for Cybersecurity

Python for Cybersecurity

Howard E. Poston, III

Publisher Resources

ISBN: 9781788992510Supplemental Content