Home > Software design >  Create multiple json files with two lists using loops
Create multiple json files with two lists using loops

Time:04-26

I want to ask how to make multiple JSON files with two lists? let's say my input is:

animal_list = ["cat", "dog", "bird", "fish", "chicken", "tiger"]
name_file = ["a", "b", "c", "d", "e", "f"]

and output that I want is:

a.json -> "cat"
b.json -> "dog"
c.json -> "bird"
d.json -> "fish"
e.json -> "chicken"
f.json -> "tiger"

so file a.json contains "cat", file b.json contains "dog" etc.

CodePudding user response:

Providing your two lists are of the same length then you could utilise zip() as follows:

list_ = ["cat", "dog", "bird", "fish", "chicken", "tiger"]
name_file = ["a", "b", "c", "d", "e", "f"]

for filename, animal in zip(name_file, list_):
  with open(f'{filename}.json', 'w') as output:
    print(animal, file=output)

CodePudding user response:

You are looking for the zip() function. It allows you to iterate over the elements of multiple lists at the same time.

From there you can open each file as a .json file using an f-string to create the file name, and then write out the contents.

To write out to the JSON format, Python has the built-in json package. This will ensure whatever Python object you want to save is formatted as proper JSON. We will use the json.dump function, which takes your content and writes it to a file object.

import json

animal_list = ["cat", "dog", "bird", "fish", "chicken", "tiger"]
name_file = ["a", "b", "c", "d", "e", "f"]

for fname, animal in zip(name_file, animal_list):
    with open(f'{fname}.json', 'w') as fp:
        json.dump(animal, fp)

CodePudding user response:

Try this:

import json

lst = ["cat", "dog", "bird"]
file_names = ["a", "b", "c"]

for file_name, content in zip(file_names, lst):
    with open(f"{file_name}.json", mode="w") as f:
        json.dump(content, f)

Basically you are zipping your two lists, then in each iteration you open a new file with the help of string formatting(you need to build the file's name) then you dump your objects with json.dump method.

Also do not use built-in names for your variable. I intentionally renamed list to lst.

  • Related