Comma separator between JSON objects with json.dump

前端 未结 2 936
陌清茗
陌清茗 2020-12-31 17:24

I am fiddling around with outputting a json file with some attributes of the files within a directory. My problem is, when appending to the file there is no separator betwe

2条回答
  •  不知归路
    2020-12-31 17:45

    I had the same problem because I needed to yield objects into a file because I didn't want to load the whole list of objects into memory. Here's my approach (but I think it's a bit hacky though):

    json_begin = '{"objects":['
    json_end = ']}'
    
    with open('file_data.txt', 'a') as outfile:
       files = os.listdir(os.curdir)
    
       outfile.write(json_begin)
    
       for f in files:
    
           extension = os.path.splitext(f)[1][1:]
           base = os.path.splitext(f)[0]
           name = f
    
           data = {
               "file_name" : name,
               "extension" : extension,
               "base_name" : base
           }
    
           json.dump(data, outfile)
           if f != files[-1]:
               outfile.write(',')
    
       outfile.write(json_end)
    

提交回复
热议问题