cascommunity.blogg.se

Python script to convert json to csv
Python script to convert json to csv











python script to convert json to csv

Without this setting, the JSON key-value pairs would be orderless, meaning each object’s properties will show in various arrangements. The argument object_pairs_hook=OrderedDict is critical here. try: print("Which file do you want to convert?") filename = input("Filename: ") extension = filename.split(".").lower() f = open(filename) if extension = "csv": # load csv file data = list(csv.reader(f)) print("CSV file loaded") elif extension = "json": # load json file data = json.load(f, object_pairs_hook=OrderedDict) print("JSON file loaded") else: print("unsupported file type. Afterwards, we’ll use the appropriate method to read in the file- csv.reader() or json.load()-while printing an error message and exiting if the file does not have the appropriate extension. We use the input function to ask the user for the file name and determine the extension by taking the last section when split based on a period (. Now let’s flesh out asking for the filename and loading the file. Assuming nothing goes wrong, the else section will execute once the try section is completed. If you’re still unsure about how the code block works, the try section will execute and if anything goes wrong the except section will take place. exiting:",e) exit() else: # convert the file and save the output Here’s the outlined structure: try: # ask for the filename # load data except Exception as e: # print error message, exit script print("Error opening file. So we’re going to use a try/except/else statement to control the flow of our script. We could do a simple input, however, if the file doesn’t exist, the rest of our script won’t work. From here, the next step is to ask for the file to load.













Python script to convert json to csv