While writing a file

I m not able to write all the jokes in file
this is my code:
from urllib.request import urlopen
api_url = ‘http://api.icndb.com/jokes
url_result = urlopen(api_url)
data = url_result.read()
#print(data)
print(type(data))

import json
json_data = json.loads(data)
print(json_data)
print(type(json_data))

for i in range(1, len(json_data[‘value’])):
data = json.dumps(json_data[‘value’][i])
print(list(data.split()))

filename=“Norris_chunk_jokes.csv”
with open(filename,‘w’,encoding=“utf-8”) as f:
for i in range(1, len(json_data[‘value’])):
data = json.dumps(json_data[‘value’][i])
#print(list(data.split()))
f.write(data)

Hey @dtele,
The problem is in your last code when you are writing to the file. If you are explicitly writing content on csv file, sure make you put \n after every line
You can try this code :

with open("filename.csv","w",encoding="utf-8") as f:
    for i in range(1, len(json_data["value"])):
        data = json_data["value"][i]
        id_ = str(data['id'])
        joke =  data['joke']
        f.write(""+id_+","+joke+"\n")

Thanks :slight_smile:

no its not working problem is that whenever I open csv file i got one joke only.

The code i have provided is working fine, you will get all jokes in different rows.

Sir, This is the code I m following and only last row i m getting where m I going wrong? why i dont get all the rows in csv file.

Code:
from urllib.request import urlopen
api_url = ‘http://api.icndb.com/jokes
url_result = urlopen(api_url)
data = url_result.read()

import json
json_data = json.loads(data)

filename=“Norris_chuk_jokes.csv”
with open(“filename.csv”,“w”,encoding=“utf-8”) as f:
for i in range(1, len(json_data[“value”])):
data = json_data[“value”][i]
id_ = str(data[‘id’])
joke = data[‘joke’]
# print(""+id_+","+joke+"\n")
f.write(""+id_+","+joke+"\n")
import pandas as pd
df = pd.read_csv(“Norris_chuk_jokes.csv”)
df.head()

OUTPUT: 619:Chuck Norris can lock a safe and keep the key inside it.

See, you are getting all the jokes in csv file.