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))

>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

Leave a Reply