-1

I need to append dictionaries to a file row by row. At the end I will have a list of dictionary in the file.

My naive attempt is:

with open('outputfile', 'a') as fout:
    json.dump(resu, fout)
    file.write(',')

But it does not work. Any suggestion?

cezar
  • 11,616
  • 6
  • 48
  • 84
Mauro Gentile
  • 1,463
  • 6
  • 26
  • 37
  • 1
    You should probably be using `fout.write(',')` instead. What format is `resu`? What errors do you get? When you say a list of dictionaries row by row, what do you mean by row? This related [SO post](https://stackoverflow.com/questions/25778021/how-can-i-save-a-list-of-dictionaries-to-a-file) might also help. – thmsdnnr Mar 09 '18 at 18:46
  • You need to be more specific, do you mean each dictionary from a list of dictionaries should be written to a line in the file? An example input and output would help. – Steve Mar 09 '18 at 19:06
  • @thmsdnnr : that was my error indeed. Thanks! – Mauro Gentile Mar 10 '18 at 17:28

1 Answers1

1

If you need to save a number of dictionaries in a particular order, why not first put them in a list object and use json to serialize the whole thing for you?

import json


def example():
    # create a list of dictionaries
    list_of_dictionaries = [
        {'a': 0, 'b': 1, 'c': 2},
        {'d': 3, 'e': 4, 'f': 5},
        {'g': 6, 'h': 7, 'i': 8}
    ]

    # Save json info to file
    path = '.\\json_data.txt'
    save_file = open(path, "wb")
    json.dump(obj=list_of_dictionaries,
              fp=save_file)
    save_file.close()

    # Load json from file
    load_file = open(path, "rb")
    result = json.load(fp=load_file)
    load_file.close()

    # show that it worked
    print(result)
    return


if __name__ == '__main__':
    example()

If your application must have you append new dictionaries from time to time, then you may need to do something closer to this:

import json


def example_2():
    # create a list of dictionaries
    list_of_dictionaries = [
        {'a': 0, 'b': 1, 'c': 2},
        {'d': 3, 'e': 4, 'f': 5},
        {'g': 6, 'h': 7, 'i': 8}
    ]

    # Save json info to file
    path = '.\\json_data.txt'

    save_file = open(path, "w")
    save_file.write(u'[')
    save_file.close()

    first = True
    for entry in list_of_dictionaries:
        save_file = open(path, "a")
        json_data = json.dumps(obj=entry)
        prefix = u'' if first else u', '
        save_file.write(prefix + json_data)
        save_file.close()
        first = False

    save_file = open(path, "a")
    save_file.write(u']')
    save_file.close()

    # Load json from file
    load_file = open(path, "rb")
    result = json.load(fp=load_file)
    load_file.close()

    # show that it worked
    print(result)
    return


if __name__ == '__main__':
    example_2()