1

I want to be able to write a script in python that will create a certain number of files/folders recursively to a certain location. So for example I want some sort of for loop that will create folder1, folder2, folder3 to a path C:\Temp. I assume a for loop is the best way to do this and using os also? Any help would be great!

1
  • for loop != recursion Commented Mar 6, 2014 at 16:31

3 Answers 3

3

Have a look at makedirs. It may help.

Sign up to request clarification or add additional context in comments.

2 Comments

Just make sure to catch exceptions from makedirs. It will raise one if it cannot create all the directories, for any reason... but also if the leaf directory existed before running it
in os.makedirs(path[, mode]) what does the mode mean? What is expected to go here?
1

Here is how to create a folder recursively and then create a file in that folder.

from pathlib import Path
import os

folder_path = Path(os.getcwd() + os.path.join('\my\folders')) #define folder structure
if not os.path.exists(path):   # create folders if not exists
    os.makedirs(path)

file_path = os.path.join(path, 'file.xlsx')  # add file to the folder path
f= open(file,"w+")                           # open in w+(write mode) or a+(append mode)

Comments

1

Since Python 3.4 you can use the pathlib to create a folder and all parent folders:

from pathlib import Path

Path("my/path/to/create").mkdir(parents=True, exist_ok=True)

If you want to raise an error on existent folder you can set exist_ok to False.

Comments

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.