简体   繁体   中英

Writing to file JSON dump from Python 'with open' exception handling

I have one dataframe "students" that I am writing to a json file if and only if the weight column in calculated_df == 100, if it does not equal to 100, then it should write to the json file an "error."

try:
    with open(input("Please enter an output path: "), 'w') as op:
        json.dump({
            'students': student_key['student'].to_list()
        }, op, indent=2)
except:
    for i, row in calculated_df.iterrows():
        if row['weight'] != 100:
    raise Exception json.dump({print("error:" "Invalid weight")},op)

I don't think you need to raise an exception. Your try statement is only valid for if the file cannot be written to (for example, permissions error)

Start with this

import json

filename = input("Please enter an output path: ")
data = {'students': student_key['student'].to_list()}
if 100 not in calculated_df['weight'].values:  # replace with correct logic; don't need a loop to check all values
  data = {"error": "Invalid weight"}

with open(filename, 'w') as op:
    json.dump(data, op, indent=2)

Or if you did want to raise , then

with open(filename, 'w') as op:
    json.dump(data, op, indent=2)
    if 'error' in data:
      raise Exception('An error occured')

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