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