Reputation: 55
I need help creating multiple sub folders in each folder inside a directory. I think I am close but I keep getting an error. I'm new to Python. Here is my code:
import os
rootpath = "C:\Users\test"
sub_folders = ['map1', 'map2', 'map3', 'map4']
folders = []
for path in os.listdir(rootpath):
folders.append(os.join.path(rootpath, path))
print folders # the folders list now contains the full path to each folder
for f in folders:
os.makedirs(os.path.join(f, folders))
I keep receiving the error message:
Traceback (most recent call last):
File "<interactive input>", line 2, in <module>
File "C:\Python27\ArcGIS10.3\lib\ntpath.py", line 66, in join
p_drive, p_path = splitdrive(p)
File "C:\Python27\ArcGIS10.3\lib\ntpath.py", line 115, in splitdrive
normp = p.replace(altsep, sep)
AttributeError: 'list' object has no attribute 'replace'
Upvotes: 4
Views: 4527
Reputation: 21643
Windows doesn't like that statement rootpath = "C:\Users\test"
for two reasons: (1) the back slashes are grouped with the succeeding characters to producing something other than you actually wanted, and (2) Windows is unwilling to allow unprivileged users to make sub-folders in the Users folder.
Here's an alternative.
>>> import os
>>> rootpath = r'c:\Users\Bill\test'
>>> os.mkdir(rootpath)
>>> os.chdir(rootpath)
>>> for sub_folder in ['map1', 'map2', 'map3', 'map4']:
... os.mkdir(sub_folder)
...
>>>
Put an r
in front of the name of the new folder so that the backwards slashes are treated literally.
Create the new subfolder with mkdir
then chdir
to it.
Now iterate through your list of subfolders and create each of them with mkdir
.
For more information about r
and raw strings from python docs:
String literals may optionally be prefixed with a letter
'r'
or'R'
; such strings are called raw strings and use different rules for interpreting backslash escape sequences
Upvotes: 3
Reputation: 55
Thank you Bill. I modified your code a bit and figured it out. Here's what I did:
import oS
root_path =r"C:\Users\sworkman\test"
sub_folders = ['Map1, Map2, Map3, Map4']
folders = []
for path in os.listdir(root_path):
folders.append(os.path.join(root_path, path))
print folders
for f in folders:
os.makedirs(os.path.join(f, folders))
for f in folders:
os.chdir(f)
for sub_folder in sub_folders:
os.mkdir(sub_folder)
I wasn't aware of the os.chdir method before. That was very helpful. Thanks again.
Upvotes: 1