rich91
rich91

Reputation: 21

Creating folders/sub-folders in python

New to coding and need some help. I've gotten so far just can't figure out how to get it to do what i need next.

import os
import subprocess
import os.path
import glob
import re
import shutil
import sys
import time

#Server Paths
test_path = 'C:\\Users\\richard.hensman\\Documents\\Test Files'

MYSGS = input("ENTER MY SGS NO: ")
BARCODE = input("ENTER BARCODE: ")
FERT = input("ENTER FERT: ")
MM = input("ENTER MM: ")
DESC = input("ENTER DESCRIPTION (NO SLASHES): ")

newfolder = os.path.join(test_path, MYSGS + "-" + BARCODE + "_" + FERT + "_" + MM + "_" + DESC)
os.makedirs(newfolder)

This creates a folder named exactly how i need it however within that folder I need 5 sub-folders: '3D Final', '3D Model', '3D Model', 'Art', 'Reference'

Finally inside sub-folder 'Art' need another sub-folder 'Supplied'

How can I do this?

Upvotes: 1

Views: 5569

Answers (3)

C.Nivs
C.Nivs

Reputation: 13106

In python 3, you can use pathlib.Path to create directories in a more object-oriented fashion:

from pathlib import Path

root = Path(test_dir)
middle = root / '_'.join((f'{MYSGS}-{BARCODE}', FERT, MM, DESC))

for folder in ('3D Final', '3D Model', '3D Model', 'Art', 'Reference'):
    end = middle / folder
    end.mkdir(exist_ok=True, parents=True)

Where the parents kwarg will do the recursive subdirectory creation, and exist_ok will allow for the upper folders to exist and skip the creation, basically handling an OSError that would otherwise be raised.

Upvotes: 0

Błotosmętek
Błotosmętek

Reputation: 12927

for subfolder in ['3D Final', '3D Model', '3D Model', 'Art', 'Reference']:
    os.makedirs(os.path.join(newfolder, subfolder))
os.makedirs(os.path.join(newfolder, 'Art', 'Supplied'))

Upvotes: 2

cs95
cs95

Reputation: 402323

Once you create that particular directory, you can navigate into it using os.chdir(...) and then create more as needed.

You'd add these lines at the end of your program:

os.chdir(newfolder)
for dir in ['3D Final', '3D Model', '3D Model', 'Art', 'Reference']:
    os.mkdir(dir)

os.mkdir(os.path.join('Art', 'Supplied'))

Upvotes: 1

Related Questions