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

Writing to json file in a for loop – python

I wrote the function as follows to save txt file in each iteration of for loop. I am calling the function called fun inside the loop. how can I save the result as a txt file? it creates file correctly but I want the name of file have txt at the end

ids = ["a1","a2","a3"]
def fun(id):
    results={}
    do something
    return results

for id in ids:
    final = fun(id)
    with open(id, 'w') as file:
        file.write(json.dumps(final)) 

if I dont call the function, saving to txt file will look like this.


final = fun(id)
import json
with open('id.txt', 'w') as file:
     file.write(json.dumps(final))

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

>Solution :

If I understood your question correctly, all you need to edit is the name of your saved files.

import json

def fun(id):
    results = 'hello world'
    return results

ids = [1, 2, 3, 4]
for id in ids:
    final = fun(id)
    with open(f"{id}.txt", 'w') as file:
        file.write(json.dumps(final)) 

The past code will save "Hellow world" in 4 files named 1.txtto 4.txt

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