python - 正确地产生和关闭文件对象

标签 python python-2.7

我有以下类(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/

相关文章:

python - OpenCV:如何用鼠标连续绘制?

python - 'if x % 2 : return True' , 如果数字可以被 2 整除,那不会返回 True 吗?

python - 如何清除Python中的输出屏幕?

python - --find-links 和 --index-url pip 标志有什么区别?

python - Python中将整数除以某个范围内的所有数字

Python Pandas groupby 多个计数

Python错误: can't install scipy.优化.brentq

python - 我正在尝试将已刮取的数据写入/粘贴到特定的 Excel 电子表格单元格位置,但我不知道如何去做

python - 替换 % 后跟字符串中的数字

python-2.7 - 尝试通过 Selenium 和 Python 使用 GeckoDriver Firefox 登录 Gmail 帐户时出现 “This browser or app may not be secure” 错误