我更改了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""")
答案 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