how to file.write() an empty string if dictionary produces a KeyError in python -
i have particular problem json files. following code reads json, , writes txt file. have shortened code readability, in real code hundereds of fields , write statements.
import os import json def _getjson(filename): """ returns list of dictionaries """ if not os.path.exists(filename): return [] open(filename, 'r') openfileobject: data = json.loads(openfileobject.read()) return data def writefile(filename, data): """writes file""" open(filename, 'w') f: d in data: f.write(d['field1'] + ' ' + d['field2'] + ' ' + d['field3'] + '\n') ## lot more code here def main(): filename = r'c:\input.json' data = _getjson(filename) outfile = r'c:\output.txt' writefile(outfile, data) if __name__ == '__main__': main()
the problem is, field not in json, , produces keyerror
while can trap try: except keyerror
. mean need put try around every field in writefile
function.
is there way without changing f.write()
statements, upon keyerror
write empty string ? (so not have capture in hundereds of try
blocks)
so dictionary problem, have no problem json itself. cannot control fields in input, 1 file may have field1
, field2
. next have three, or one. json part works, missing fields, sometimes.
use dict.get
:
f.write(d.get('field1', '') + ' ' + d.get('field2', '') + ' ' + d.get('field3', '') + '\n')
get()
returns value key, or given default or none
.
Comments
Post a Comment