0

I am trying to write a script, that will look for folders in the current directory, once found, it will check to see if the folder contains the following folders: 'Contracts' & 'Other Documents', if these are found the folder can be ignored. If not, I need to have the script make these folders.

This is what I have so far:

import os
import sys

folders_to_be_made = ['Contracts', 'Other Documents']

for folder in os.listdir('.'):
    if os.path.isdir(folder):
        filepath = os.path.join(os.getcwd(), folder)
        print filepath

Can anyone please advise on how I would go about creating the folder if missing.

Thank you.

Dylan Logan
  • 195
  • 16
  • 1
    What is the actual question? – Elbenfreund Mar 16 '18 at 11:15
  • 1
    You may want to check out this similar question on SO: [How can I create a directory if it does not exist?](https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist) – jkm Mar 16 '18 at 11:16

2 Answers2

0

This should help.

import os
import sys

folders_to_be_made = ['Contracts', 'Other Documents']

for folder in os.listdir('.'):
    if os.path.isdir(folder):
        filepath = os.path.join(os.getcwd(), folder)
        l2 = os.listdir(filepath )
        for i in folders_to_be_made:     
            if i not in l2:            #Check if folder is in dir. if not create
                os.mkdir(os.path.join(filepath , i))
Rakesh
  • 75,210
  • 17
  • 57
  • 95
0

Maybe define a working directory : e.g current_dir = os.getcwd()

You have to iterate through the directories (eg : "1", "2", "3") and check if they already contain the folders_to_be_made if not create it with os.makedirs . To check if a directory exists and create it @jkm provides you a link to an another SO question.

This code should help:

import os 

folders_to_be_made = ['Contracts', 'Other Documents']

for dirfile in os.listdir(current_dir):
    # if dirfile is a folder check its content 
    if os.path.isfile(dirfile):
        continue

    lfolders = os.listdir(dirfile)
    # folder "i" empty 
    if lfolders == []:
        for dirtomake in folders_to_be_made:
            os.makedirs(os.path.join(os.path.abspath(dirfile), dirtomake))
        continue

    for folder in lfolders:
        for dirtomake in folders_to_be_made:
            if dirtomake not in lfolders:
                os.makedirs(os.path.join(os.path.abspath(dirfile), dirtomake))