Home > Software engineering >  Output results as csv file
Output results as csv file

Time:12-12

Can you help me output the result to a csv file?

import requests
import xml.etree.ElementTree as ET
import datetime

response = requests.get('https://publicacionexterna.azurewebsites.net/publicaciones/prices')
myroot = ET.fromstring(response.content)

print(f"Place_id\tItem\tPrice\tDate")

for x in myroot.findall('place'):
         place_id = x.get('place_id')
         item = x.find('gas_price').attrib['type']
         price = x.find('gas_price').text
         today = datetime.date.today()
         print(f"{place_id}\t{item}\t{price}\t{today}")

thanks for your help

CodePudding user response:

  • Create a header list Create row list
  • Add Each row as a list to dataList
  • Open file and Write headerlist
  • Writerow data to the opened file

Main.py :

import csv
import requests
import xml.etree.ElementTree as ET
import datetime

response = requests.get('https://publicacionexterna.azurewebsites.net/publicaciones/prices')
myroot = ET.fromstring(response.content)

print(f"Place_id\tItem\tPrice\tDate")

headerlist = ["Place_id","Item","Price","Date"]  # added a header list

dataList = [] # empty list to place each row

for x in myroot.findall('place'):
    rowList =[] # empty row list to add individual data
    
    place_id = x.get('place_id')
    rowList.append(place_id)  # append place id
    item = x.find('gas_price').attrib['type']
    rowList.append(item) # append item
    price = x.find('gas_price').text
    rowList.append(price) # append price
    today = datetime.date.today()
    rowList.append(today) # append today
    dataList.append(rowList) # append the entire row as a lit to data list


with open('example.csv', 'w', newline='') as file: # open csv file 
      write = csv.writer(file)
      write.writerow(headerlist) # write header data
      write.writerows(dataList) # write each row

CodePudding user response:

You can use a list comprehension to build a list of dictionaries, and pass it to a pandas dataframe:

import pandas as pd

data = [{
  "place_id": x.get('place_id'),
  "item": x.find('gas_price').attrib['type'],
  "price": x.find('gas-price').text,
  "today": datetime.date.today()
}, for x in myroot.findall('place')]

df = pd.DataFrame(data)
df.to_csv("Output_csv_file.csv")

The downside is that you would have to install a third party library (pandas), but this an easy, high-level solution, I hope it helps!

  • Related