Michal
Michal

Reputation: 43

Python 3.5 - Create folder with subfolder under Windows

Is there some elegant way how to create Windows path as follows.

home_dir = ('C:\First\Second\Third')        
if not os.path.exists(home_dir):
    os.mkdir(home_dir)
    print("Home directory %s was created." %home_dir)

I am able to create in single steps "C:\First" then "Second" etc ...

With this code I am getting:

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\First\Second\Third'

Upvotes: 3

Views: 9368

Answers (2)

Kenly
Kenly

Reputation: 26688

To create a folder with subfolders use:

os.makedirs(home_dir)

Upvotes: 3

Idos
Idos

Reputation: 15310

You should check the existence of a directory path with os.path.isdir:

Return True if path is an existing directory.

os.path.isdir("C:\First\Second\Third")

This will avoid the FileNotFoundError.

Then create the dirs. It looks like so:

home_dir = ('C:\First\Second\Third')        
if not os.path.isdir(home_dir):
    os.makedirs(home_dir)
    print("Home directory %s was created." %home_dir)

Upvotes: 5

Related Questions