Kashif Iqbal
Kashif Iqbal

Reputation: 153

Current directory path in python changed in the class

I change the directory in the dirStuff.findFileInDir function, but when I print out the current working directory in jsonParsing.printDirtyJSON it gives me the (new) directory I changed to.

I thought classes were self-contained. I want the path to the old directory, before I changed. The dirStuff class is called before the the jsonParsing class. Thanks.

class dirStuff:
    def __init__(self, dirName): 
        self.dirName = dirName

    def doesDirExit(self):
        isLuisModelDir = os.path.isdir(self.dirName)
        if isLuisModelDir:
            print("""directory exists - Calling the findFileInLuisDir function""")
        else:
            print("****directory does not exist. Exiting****")
            sys.exit()        

    def findFileInDir(self):
        print("found the directory containing the utterances")
        os.chdir(self.dirName)
        luisModelList=[]
        for file in glob.glob("*.JSON"):
            luisModelList.append(file)
        return luisModelList            


class jsonParsing:
    def __init__(self, dirName, fileName):
        self.dirName = dirName
        self.fileName = fileName

    def printDirtyJSON(self):
        luis_model_json = json.loads(open(self.fileName[1], encoding="utf8").read())

        #open output file
        try:
            utterances_output = open('utterances.txt', "w", encoding="utf8")
            # redirect utterances to the output file
            print(os.getcwd())
            for i in range(len(luis_model_json['utterances'])):
                utterances = luis_model_json['utterances'][i]['text']
                #print(utterances)            
                utterances_output.write(utterances+"\n")
                #close the file    
            utterances_output.close()
        except IOError:
            print(""" Could not open the utterances file to write to""")

Upvotes: 1

Views: 1850

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140216

os.chdir changes the current directory for the whole process. If you can avoid it, do it.

In that case you can. Replace this code:

def findFileInDir(self):
    print("found the directory containing the utterances")
    os.chdir(self.dirName)
    luisModelList=[]
    for file in glob.glob("*.JSON"):
        luisModelList.append(file)
    return luisModelList

by that code, which does exactly the same thing but without the need to change directory:

def findFileInDir(self):
    print("found the directory containing the utterances")
    luisModelList=[]
    for file in glob.glob(os.path.join(self.dirName,"*.JSON")):
        luisModelList.append(os.path.basename(file))
    return luisModelList

or more compact, using list comprehension:

def findFileInDir(self):
    print("found the directory containing the utterances")
    return [os.path.basename(file) for file in glob.glob(os.path.join(self.dirName,"*.JSON"))]

another way, using os.listdir() and fnmatch module (os.listdir doesn't add current directory to the output):

def findFileInDir(self):
    print("found the directory containing the utterances")
    return [file for file in os.listdir(self.dirName) if fnmatch.fnmatch(file,"*.JSON")]

A generic alternative would be to store the old path, perform the chdir, and restore the previous path:

previous_path = os.getcwd()
os.chdir(new_path)
...
os.chdir(previous_path)

but you have to handle exceptions (put the path restoration in a finally block) to avoid that your path stays set to the wrong value if an error occurs. I don't recommend it.

Upvotes: 1

Seif
Seif

Reputation: 1097

If you want to keep the same code and logic, you can do these edits:

class dirStuff:
    def __init__(self, dirName): 
        self.dirName = dirName
        self.currentDirName = os.getcwd()

.....


class jsonParsing:
    def __init__(self, dirName, fileName, dirStuffObj):
        self.dirName = dirName
        self.fileName = fileName
        self.currentDirName = dirStuffObj.currentDirName

With dirStuffObj an instance of dirStuff

Upvotes: 0

Related Questions