There is a person folder in it age1 folder, how to create a folder in the age1 folder, let's say Gulag ?
|
2 answers
Use os.makedirs . With it, you can specify the whole path from the folders that will then be created:
import os name1 = 'Gulag' os.makedirs('person/age1/{}'.format(name1), exist_ok=True) - Why should I create packs that have already been created? - Maxim Khalin
- I have the
personandage1created. I need to create a folder with the name I entered in theage1folder which is located in thepersonfolder - Maxim Khalin - It works like
mkdir -p. If the directory exists, it creates the next one in the path, if not it creates it and creates the next one in it - Andrey - If the parameter
exist_ok=Trueis specified, thenmakedirsdoes not create folders that already exist. Instead, it uses this path to create folders on it. - Jazzis - Gulag folder is not created - Maxim Khalin
|
In the 2nd, makedirs creates intermediate directories without specifying additional parameters. Added a check for the existence of the created directory:
import os def create_folder(workspace, folder): path = os.path.join(workspace, folder) if not os.path.exists(path): os.makedirs(path) print "create folder with path {0}".format(path) else: print "folder exists {0}".format(path) #create_folder("person/age1", "Gulag") create_folder(r"C:\TEMP\person\age1", "Gulag") # create folder with path C:\TEMP\person\age1\Gulag - oneuncomment the line
create_folder("person/age1", "Gulag")Writes that the folder exists, although it does not exist - Maxim Khalin - onemost likely you are confused with relative paths, use absolute paths - Eugene Dennis
|
pathlib.Path('/person/age1/Gulag').mkdir(parents=True, exist_ok=True)- Akinapathlib.Path('/person/age1/{0}'.format(name1)).mkdir(parents=True, exist_ok=True)- Maxim Khalinimport pathlib, Version 3.7 - Maxim Khalin