3

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'

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

For Python 3.2+ you can also use os.makedirs(home_dir, exist_ok=True). This creates all directories in the path, if necessary, and won't raise FileExistsError if the leaf directory already exists.
3

To create a folder with subfolders use:

os.makedirs(home_dir)

2 Comments

I tried to use os.makidirs before and was getting exactly the same error. I see now that the problem I had was somehow corrupted file with my code. At the momement when I try to execute I am getting (unicode error) cant decode bytes. Anyway, creating New File resolved the problem and this works as expected. Thank you for quick response.
@Michal if you specifyed a path like c:\dir1\dirs2 and if dir1 does not exist it will fail (The specified path was not found)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.