简体   繁体   中英

How can I read a file that contains a list of dictionaries into python?

I've created a file that contains a list of dictionaries that I was working with. Unfortunately, I'm not sure how to re-import that file back into python in that same format.

I initially wrote the file out as JSON and as text, like this:

d = list_of_dics
jsonarray = json.dumps(d)

with open('list_of_dics.txt', 'w') as outfile:
    json.dump(jsonarray, outfile)

with open('list_of_dics.json', 'w') as outfile:
    json.dump(jsonarray, outfile)

Can anyone suggest a way to re-import these into python in the same format — ie, a list of dictionaries?

You're using json.dump() incorrectly. You should be passing d to it directly, not the output of json.dumps(d) . Once you do that, you can use json.load() to retrieve your data.

with open('list_of_dics.txt', 'r') as infile:
    d = json.load(infile)

With

json.dumps(d)

you've (JSON-)encoded list d in a string (which you assign to a variable misleadingly called jsonarray ).

With

json.dump(jsonarray, outfile)

you've JSON-encoded that string and written the result to outfile .

So it's now (unnecessarily) doubly JSON-encoded in the files list_of_dics.txt and list_of_dics.json .

To cleanly get it back from there (without resorting to manual string manipulation ) you have to decode it twice:

import json

with open('list_of_dics.json', 'r') as infile:
    recovered_d = json.loads(json.load(infile))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM