0

我必须使用python读取一个大小为3 Gb的大型json文件。json文件中的数据之间有一个垃圾值'] ['。对于体积较小的文件,我使用下面的脚本来修剪垃圾值。

filename=r'C:\Users\user1\Downloads\samplefile.json'
    with open(filename, encoding="utf8") as json_file:
        data = json_file.read()
data=data.replace('][',',')

对于大型文件,我使用下面的脚本来读取文件,并在处理较小的文件时使用上面的脚本处理了以下错误。

脚本:

import ijson
f=ijson.items(open(r'C:\Users\user1\Downloads\samplefile.json','r'),'item')

错误:

IncompleteJSONError: 解析错误: 尾随垃圾 82220.00,"NUMBER":1799106.00}][{"DATE":"2021092412504700000 (就在这里) ------^

我还使用了 pandas 的 read_json 来阅读它,但最终得到了同样的错误。关于如何修剪这个垃圾值的任何想法都会非常有帮助。我没有共享文件或一些样本,因为这些文件是在安全系统中使用的。

我已经尝试使用下面提到的文件包装类,但仍然再次出现内存错误

import ijson

class Foo(object):
    def __init__(self, fpath, mode , encoding):
        self.f = fpath
        self.mode = mode
        self.encoding = encoding
    def __enter__(self):
        print ('context begun')
        self.file = open(self.f, self.mode,encoding=self.encoding)
        self.file=self.file.read().replace('][',',')
        return self.file
    def __exit__(self, exc_type, exc_val, exc_tb):
        print ('closed')

        

with Foo(r'C:\Users\user1\Downloads\samplefile.json','r',encoding='utf-8') as json_file:
    objects = ijson.items(json_file, 'items')
4

0 回答 0