How can I create a directory if it does not exist using Python? (2024)

Python has built in file creation, writing, and reading capabilities. In Python, there are two sorts of files that can be handled: text files and binary files (written in binary language, 0s, and 1s). While you can create files you may delete them when you no longer need them.

It is simple to create directories programmatically, but you must ensure that they do not already exist. You'll have difficulties if you don't.

Example 1

In Python, use the os.path.exists() method to see if a directory already exists, and then use the os.makedirs() method to create it.

The built in Python method os.path.exists() is used to determine whether or not the supplied path exists. The os.path.exists() method produces a boolean value that is either True or False depending on whether or not the route exists.

Python's OS module includes functions for creating and removing directories (folders), retrieving their contents, altering and identifying the current directory, and more. To interface with the underlying operating system, you must first import the os module.

#python program to check if a directory existsimport ospath = "directory"# Check whether the specified path exists or notisExist = os.path.exists(path)#printing if the path exists or notprint(isExist)

Output

On executing the above program, the following output is generated.

TrueLet’s look at a scenario where the directory doesn’t exist.

Example 2

The built in Python method os.makedirs() is used to recursively build a directory.

#python program to check if a directory existsimport ospath = "pythonprog"# Check whether the specified path exists or notisExist = os.path.exists(path)if not isExist: # Create a new directory because it does not exist os.makedirs(path) print("The new directory is created!")

Output

On executing the above program, the following output is generated.

The new directory is created!

Example 3

To create a directory, first check if it already exists using os.path.exists(directory). Then you can create it using −

#python program to check if a path exists#if it doesn’t exist we create oneimport osif not os.path.exists('my_folder'): os.makedirs('my_folder')

Example 4

The pathlib module contains classes that represent filesystem paths and provide semantics for various operating systems. Pure paths, which give purely computational operations without I/O, and concrete paths, which inherit from pure pathways but additionally provide I/O operations, are the two types of path classes.

# python program to check if a path exists#if path doesn’t exist we create a new pathfrom pathlib import Path#creating a new directory called pythondirectoryPath("/my/pythondirectory").mkdir(parents=True, exist_ok=True)

Example 5

# python program to check if a path exists#if path doesn’t exist we create a new pathimport ostry: os.makedirs("pythondirectory")except FileExistsError: # directory already exists pass

Updated on: 06-Jun-2024

278K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started

How can I create a directory if it does not exist using Python? (2)

Advertisem*nts

How can I create a directory if it does not exist using Python? (2024)
Top Articles
6 Types of Investors for Startups | BaseTemplates
Tailor Your Pitch: Enticing Angel Investors & VCs
Condogames Xyz Discord
The Miami Herald from Miami, Florida
Pocatello Temple Prayer Roll
Scott Surratt Salary
Jewel-Osco Pharmacy Locations
Q-global Web-based Administration, Scoring, and Reporting
Temu Codes 2022
Hygeia: The Greek Goddess of Health | History Cooperative
Laveen Modern Dentistry And Orthodontics Laveen Village Az
Final Fantasy VIII – Guide and Walkthrough
Richard Sambade Obituary
Self-Help for Sobriety Without Relapse
Dallas Probation Mockingbird
Ewwwww Gif
Styleseat Near Me
Peg Leg Pete's Reservations
Lakeview Docks Jet Ski Rentals
Crime | Denver Daily Voice
Theplantfammm
Jabcomix News
19 Dollar Fortnite Card Copypasta
Directions To 295 North
Siriusxm Patriot Schedule
Morse Road Bmv Hours
Great Clips Grandview Station Marion Reviews
866-392-8015
Academic Calendar | Touro University Worldwide
Nh. Craigslist
Conan Exiles: Cheats und Kommandos für das Game
Why Is 365 Market Troy Mi On My Bank Statement
Craigslist Pets Sac
Bulloch County Police Reports
Ft86 Club
Lenscrafters Westchester Mall
Violent Night Showtimes Near Amc Fashion Valley 18
Lbl A-Z
Craigslist Bay Area For Sale
763-298-8022
Crowes Pasture Tide Chart
Ronan Keating - Steckbrief, Biografie, Musik, TV, Privatleben und News
Amari Cooper Pfr
Mythical Horses (Tier 10) - BDFoundry
Megan Mullally | Rotten Tomatoes
Ter Review
Jeff Monreal Funeral Home Obituaries
24 Hour Lock Up Knoxville Tn
Best Town Hall 11
Overton's Free Catalog
2021 GMC Sierra 2500HD AT4 4x4Crew diesel for sale - Kernersville, NC - craigslist
Craigslist Metal Roofing
Latest Posts
Article information

Author: Arielle Torp

Last Updated:

Views: 6390

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.