【问题标题】:Current directory path in python changed in the classpython中的当前目录路径在类中更改
【发布时间】:2017-01-20 15:19:39
【问题描述】:

我更改了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 为所有类更改它

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


【解决方案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 块中)以避免发生错误时您的路径保持设置为错误值。不推荐。

【讨论】:

    【解决方案2】:

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

    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
    

    dirStuffObjdirStuff 的一个实例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多