I recently just started using argparse and I'm trying to use it to open a json file among other things like outputting into a csv file.
import argparse
import os
import json
import csv
import pandas as pd
parser = argparse.ArgumentParser(description='Json to Csv')
parser.add_argument('file', type=argparse.FileType('r'))
#parser.add_argument('file', type=str)
args = parser.parse_args()
with args.file as json_data:
print(json_data)
#argparse_dict = vars(args)
#argparse_dict.update(json_data)
baseline_dict = {}
try:
baseline_dict = json.load(json_data)
except:
print("JSON Baseline File {}: Unable to LOAD")
results_dict = baseline_dict["results"]
"""with open(args.file) as json_data:
baseline_dict = {}
try:
baseline_dict = json.load(json_data)
except:
print("JSON Baseline File {}: Unable to LOAD")"""
#Turns the new dictionary into a dataframe df = pd.DataFrame(results_dict)
When I try to open the json file using argparse in terminal I get this error. I know it's pulling the json file because I can get it to run before calling it as json_data.
with args.file as json_data:
JSON Baseline File {}: Unable to LOAD
Traceback (most recent call last):
forloop makes no sense. If you want the value for a key named"results", just doresults_dict = baseline_dict["results"](orresults_dict = baseline_dict.get("results", {})if the"results"key might not exist and you want to silently use an emptydictin that case) and remove all the code fromresults_dict = {}todel (baseline_dict), which has multiple errors in it.FileTypeuse; letargparsegive you a filename (string), which you can thenwith openand load. With the modern preference forwith open,FileTypeis obsolete.argparsecatch the exceptions and convert to a useful error message for you is super-convenient. Sure, you need to addwithyourself, but for scripts (as opposed to libraries), you have top-level control so the issues are fairly limited.open, not the call toopenitself, that lets thewithstatement ensure it gets closed.