There is a person folder in it age1 folder, how to create a folder in the age1 folder, let's say Gulag ?

  • one
    pathlib.Path('/person/age1/Gulag').mkdir(parents=True, exist_ok=True) - Akina
  • @Akina Does not create, in my case, I enter the name of the directory myself. It turns out this pathlib.Path('/person/age1/{0}'.format(name1)).mkdir(parents=True, exist_ok=True) - Maxim Khalin
  • @Akina and nothing is created, the folder person and age1 have already been created, it is necessary that a folder be created there - Maxim Khalin
  • one
    Library did not forget to import? and specify the exact version of python. - Akina
  • @Akina Library imported import pathlib , Version 3.7 - Maxim Khalin

2 answers 2

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 person and age1 created. I need to create a folder with the name I entered in the age1 folder which is located in the person folder - 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=True is specified, then makedirs does 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 
  • one
    uncomment the line create_folder("person/age1", "Gulag") Writes that the folder exists, although it does not exist - Maxim Khalin
  • one
    most likely you are confused with relative paths, use absolute paths - Eugene Dennis