python中的当前目录路径在类中更改

时间:2017-01-20 15:19:39

标签: python python-3.x class directory chdir

我更改了dirStuff.findFileInDir函数中的目录,但是当我打印出jsonParsing.printDirtyJSON中的当前工作目录时,它给了我更改为的(新)目录。

我认为课程是自成一体的。在我改变之前,我想要旧目录的路径。在dirStuff类之前调用​​jsonParsing类。谢谢。

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""")

2 个答案:

答案 0 :(得分:1)

os.chdir更改整个过程的当前目录。如果你能避免它,那就去做吧。

在这种情况下你可以。替换此代码:

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

通过该代码完成相同的操作,但无需更改目录:

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

或更紧凑,使用列表理解:

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"))]

另一种方法,使用os.listdir()fnmatch模块(os.listdir不会将当前目录添加到输出中):

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

通用替代方法是存储旧路径,执行chdir并恢复上一个路径:

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

但是您必须处理异常(将路径恢复放在finally块中)以避免在发生错误时将路径设置为错误的值。我不推荐它。

答案 1 :(得分:0)

如果您想保留相同的代码和逻辑,可以进行以下编辑:

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

使用dirStuffObj dirStuff

的实例