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!
3 Answers
Have a look at makedirs. It may help.
2 Comments
Ricardo Cárdenes
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 ituser2177781
in os.makedirs(path[, mode]) what does the mode mean? What is expected to go here?
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
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.