Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python for loop only writes one json file

I am trying to write a Python script that writes x amount of files in a for loop, but at the moment it only writes a single file, item-{x}.json, instead of 110. How can I fix it?

import json
  
for x in range(110):
    dictionary = {
        "name":"Item #{x}",
        "properties":{
            "creators":[
                {
                    "address":"H5ZQGeTv23nJRcFmEprRLuM9cTeJMajYvf2k1JhuLhE2",
                    "share":100
                }
            ]
        },
    }
  
    json_object = json.dumps(dictionary, indent = 2)
    with open("item-{x}.json", "w") as outfile:
        outfile.write(json_object)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

use f-strings like this:

import json
  
for x in range(110):
    dictionary = {
        "name":f"Item #{x}",
        "properties":{
            "creators":[
                {
                    "address":"H5ZQGeTv23nJRcFmEprRLuM9cTeJMajYvf2k1JhuLhE2",
                    "share":100
                }
            ]
        },
    }
  
    json_object = json.dumps(dictionary, indent = 2)
    with open(f"item-{x}.json", "w") as outfile:
        outfile.write(json_

object)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading