I have a python script that pulls from a 3 rd party API. The script runs for 3 different cities in loop and creates a data frame for each city. Then I transfer the data frame to an excel sheet as a tab. Below is the code.
sublocation_ids = [
{
"id": 163,
"name": "Atlanta, GA"
},
{
"id": 140,
"name": "Austin, TX"
},
{
"id": 164,
"name": "Baltimore, MD"
}
]
filter_text = "(headline:coronavirus OR summary:coronavirus OR headline:covid-19 OR summary:covid-19) AND categories:{}"
writer = pd.ExcelWriter(excel_path)
for sub in sublocation_ids:
city_num_int = sub['id']
city_num_str = str(city_num_int)
city_name = sub['name']
filter_text_new = filter_text.format(city_num_str)
data = json.dumps({"filters": [filter_text_new], "sort_by":"created_at", "size":2})
r = requests.post(url = api_endpoint, data = data).json()
articles_list = r["articles"]
articles_list_normalized = json_normalize(articles_list)
df = articles_list_normalized
df['publication_timestamp'] = pd.to_datetime(df['publication_timestamp'])
df['publication_timestamp'] = df['publication_timestamp'].apply(lambda x: x.now().strftime('%Y-%m-%d'))
df.to_excel(writer, sheet_name = city_name)
writer.save()
The current issue I am facing is only one tab is getting created in the excel sheet for the first city "Atlanta,GA" I pull the data for from the API. How to create the tab for each and every city in the directory or does my code has any issue?
writer.save()with every loop thus overwriting the sheet each time. call it at the end of your loop