0

ファイルのグループがあり.jsonl.gzます。スクリプトを使用してそれらを読むことができます:

 import json
 import gzip
 with gzip.open(filepath, "r") as read_file:  # file path ends with .jsonl.gz
     try:
         # read gzip file which contains a list of json files (json lines)
         # each json file is a dictionary of nested dictionaries
         json_list = list(read_file)
     except:
         print("fail to read thezip ")

次に、いくつかの処理を行い、いくつかの .json ファイルを取得してリストに保存します。

for num, json_file in enumerate(json_list):        
        try:
            j_file = json.loads(json_file)
            (...some code...)
        except:
           print("fail")

私の質問は、それらをもう一度書き込む正しい方法は何.jsonl.gzですか?

これは私の試みです

jsonfilename = 'valid_' +str(num)+'.jsonl.gz'
with gzip.open(jsonfilename, 'wb') as f:
     for dict in list_of_nested_dictionaries:
         content.append(json.dumps(dict).encode('utf-8'))
     f.write(content)

しかし、私はこのエラーが発生しました: TypeError: memoryview: a bytes-like object is required, not 'list'

次に、辞書のリストをそのまま gzip しようとしました。

jsonfilename = 'valid_' +str(num)+'.jsonl.gz'
with gzip.open(jsonfilename, 'wb') as f:
    f.write(json.dumps(list_of_nested_dictionaries).encode('utf-8'))

しかし、リスト全体を1つのブロックとしてgzipするという問題があり、それを読み返すと、最初のステップから取得したjsonファイルのリストではなく、保存されたリスト全体である1つの要素を取得しました。

これは私が読むために使用するコードです

with gzip.open('valid_3.jsonl.gz', "r" , ) as read_file:
    try:
        json_list = list(read_file) # read zip file
        print(len(json_list))# I got 1 here
    except:
        print("fail")
json_list[0].decode('utf-8')
4

2 に答える 2

0

f.write(content)バイト文字列を取りますが、バイト文字列のリストを渡しています。

f.writelines(content)リストから各バイト文字列を反復して書き込みます。

編集:ちなみに、gzipは単一のファイルを圧縮するためのものです。複数のファイルを 1 つに圧縮する必要がある場合は、最初にそれらをtarballにまとめてから gzip することをお勧めします。

于 2020-05-01T21:38:24.170 に答える