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



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

>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块中),以避免在发生错误时路径保持设置为错误值。我不推荐它。

如果要

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

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

最新更新