Python Forum
create folders named from list array - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: create folders named from list array (/thread-11637.html)



create folders named from list array - HaKDMoDz - Jul-19-2018

Hi,

how can i create a bunch of folders in my specified location and create these folders based on a list of folder names to be created

example my cwd is:

c:\xampp\htdocs\site\

my list of folders to be created inside the cwd is:

  folderstobecreatedlist = (['folder1', 'folder2', 'folder3', 'etc'])  
so my desired outcome would be example:

c:\xampp\htdocs\site\folder1
c:\xampp\htdocs\site\folder2
c:\xampp\htdocs\site\folder3
c:\xampp\htdocs\site\etc

i have tried:

import os
currentpath = "c:\xampp\htdocs\site\"
listOfFoldersToCreate = ['folder1', 'folder2', 'folder3', 'etc']
os.mkdir(currentpath, mode=777
os.mkdir(currentpath, mode)
os.mkdir(currentpath, mode, listOfFoldersToCreate
for foldersToCreate in listOfFoldersToCreate:
    os.mkdir(path, mode)
but as one can tell i have no experience in python and would really like some help please. preferably in a for loop to just iterate over my list of folders to create and make it done


RE: create folders named from list array - buran - Jul-19-2018

you need to loop over elements in the list, for each folder name from the list construct the folder path and then use os.mkdir to create the folder.
Also please, don't put every separate line in python tags. Show us the full code as one piece.

import os

folders = ['folder1', 'folder2', 'folder3', 'etc']
base_path = 'c:/xampp/htdocs/site/' # use raw string if you would use backslash e.g. r'c:\xampp\htdocs\site\'
for folder in folders:
    os.mkdir(os.path.join(base_path, fodler))

or if you prefer OOP approach
from pathlib import Path

folders = ['folder1', 'folder2', 'folder3', 'etc']
base_path = 'c:/xampp/htdocs/site/' # use raw string if you would use backslash e.g. r'c:\xampp\htdocs\site\'
for folder in folders:
    Path(base_path, folder).mkdir()