Reputation: 469
I am trying to export a dict to a csv. I am pulling data from an api and need it to print to a CSV.
I am using:
import datetime
import csv
import pendulum
import requests
from tabulate import tabulate
import pandas as pd
import numpy as np
The API I am calling is below:
api_url = "https://secure-webtv-static.canal-plus.com/metadata/cpfra/all/v2.2/globalchannels.json"
response = requests.get(api_url).json()
Getting the data I would like to pull is here:
tv_programme = {
channel["name"]: [
[
e['title'],
e['subTitle'],
pendulum.parse(e['timecodes'][0]['start']
).time().strftime("%H:%M"),
datetime.timedelta(
milliseconds=e['timecodes'][0]['duration'],
).__str__().rsplit(".")[0],
] for e in channel["events"]
] for channel in response["channels"]
}
I am trying to use Pandas to send the data to the CSV
file
df = pd.DataFrame(tabulate(
tv_programme["CANAL+ SPORT"],
headers="firstrow"("Title", "Subtitle", "Time", "Duration"),
tablefmt="csv",
))
print(tabulate(
tv_programme["CANAL+ SPORT"],
headers=["Title", "Subtitle", "Time", "Duration"],
tablefmt="csv",
))
df = pd.DataFrame(sorted(list(tv_programme.headers('sports.csv'))))
The print
collects the below data and I need this to populate the CSV
file.
Title Subtitle Time Duration
----------------------------------- ----------- ------ ----------
Sport Reporter Doc Sport 10:42 0:26:23
Chelsea / West Ham 14e journée 11:11 0:48:38
Cesta punta - Pro Tour 2020 Autre Sport 12:51 1:28:53
Rugby - Golden Lions / Natal Sharks 4e journée 14:20 0:45:56
Rugby - Colomiers / Perpignan 8e journée 15:55 0:50:00
Rugby - Oyonnax / Biarritz 6e journée 17:55 0:50:00
Rugby - Castres / Brive 4e journée 19:55 1:15:00
Now this is where I am getting stuck and receiving the error: TypeError: 'str' object is not callable
Upvotes: 0
Views: 87
Reputation: 20042
You need to pass the actual data structure, not the string that's built by tabulate
.
For example:
df = pd.DataFrame(tv_programme["CANAL+"], columns=["Title", "Subtitle", "Time", "Duration"])
df.to_csv("canal_plus.csv", index=False)
This gives you:
Upvotes: 1