我有以下类(class):
class JsonIterator(object):
def __init__(self,folder):
self.root = os.path.join(os.getcwd(), folder)
self.fis = [fi for fi in os.listdir(folder) if "lyrics" in fi]
def __iter__(self):
i = 0
with open(os.path.join(self.root,self.fis[i])) as f:
yield json.load(f)
i += 1
它没有按照我想要的方式工作——它似乎没有超出第一个文件。我试过了
def __iter__(self):
i = 0
f = open(os.path.join(self.root, self.fis[i]))
js = json.load(f)
f.close()
yield js
i += 1
但无论哪种方式,len(list(JsonIterator("path/to/myfolder")))
都会给我 1
,而且我知道有一个事实文件夹中有多个文件。当然,另一种选择是
def __iter__(self):
i = 0
yield json.load(open(os.path.join(self.root, self.fis[i])))
i += 1
但是所有那些悬而未决的打开文件占用了太多内存,我的进程被杀死了。
那我该怎么办呢?我考虑过编写某种装饰器,但我并不真正理解它们是如何工作的,或者即使它能解决我的问题。
谢谢!
最佳答案
您需要遍历 self.fis
中的文件名:
class JsonIterator(object):
def __init__(self,folder):
self.root = os.path.join(os.getcwd(), folder)
self.fis = [fi for fi in os.listdir(folder) if "lyrics" in fi]
def __iter__(self):
for fi in self.fis:
with open(os.path.join(self.root, fi)) as f:
obj = json.load(f)
yield obj
关于python - 正确地产生和关闭文件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15645819/