Search code examples
pythondirectorypathoperating-systemmkdir

Python, how to create dir within dir?


I'm trying to create a directory(workdir2) which is in the 'workdir1' directory I made. In this situation, what can I do ?

input_file: name

input_file.txt

Code:

import os
target_name=os.path.basename(input_file).strip().split('.')[0]
workdir1=os.mkdir(target_name + '_prep')
workdir2=os.mkdir('output_file_prep')

Expected result: made path:

./input_file_prep/output_file_prep/

Solution

  • You can use mkdirs

    import os
    
    input_file = "something.txt".split(".")[0]
    
    
    def mkdirp(path):
        try:
            os.makedirs(path, exist_ok=True)
            print("Done")
        except Exception as e:
            print(e)
    
    
    mkdirp(f'./{input_file}_prep/output_file_prep')