0

I have a folder which consists of 50+ other folders. I need os.chdir to check the first folder, take a step back, check folder #2, take a step back, check folder #3 and so on...

My code so far only checks the hard-coded folder but I don't know how to automate it so that it checks each folder in a sequence.

facility_types = ["4x Clinic", "4x Hospital", "4x Lab"]


for mnemonic in os.listdir():
    print (mnemonic)
    print (os.listdir(mnemonic))
    individual_facility = os.listdir(mnemonic)

    for facility in facility_types:
        if individual_facility not in os.listdir(mnemonic):
            os.chdir("C:/Users/mf050034/Desktop/test/Client 1")
            os.makedirs(facility)
        else: 
            print ("All Facility Types Already Exits.")
            continue
            for facility in facility_types:
                if individual_facility not in os.listdir(mnemonic):
                    os.chdir(+ 1)
                    os.makedirs(facility)
                else: 
                    print ("All Facility Types Already Exits.")
                    break
3
  • I don't have the time/patience to work out a full example right now, but you might find docs.python.org/2/library/os.html#os.walk useful. Commented Dec 27, 2016 at 22:13
  • What do you mean by "take a step back"? Do you want to keep checking parent folders up to the root of the drive? Commented Dec 27, 2016 at 22:29
  • @tdelaney check root --> go to level 1 --> check root --> check level 1. Automating that, I have os.chdir(+ 1), I tried os.chdir("..") neither worked Commented Dec 27, 2016 at 22:47

1 Answer 1

2

Looks like you're trying to look at each directory (facility) in the current directory and if it doesn't have an item from facility_types in it, create it as a directory.

import os

facility_types = ["4x Clinic", "4x Hospital", "4x Lab"]

for facility in os.listdir():
    for facility_type in facility_types:
        if facility_type not in os.listdir(facility):
            print("Adding Facility Type '{}' to {}".format(
                  facility_type, facility))
            os.makedirs('{}/{}'.format(facility, facility_type))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.