-1

I extract some data from a url but I can't create a csv with that. When I try to save it into a csv each character is in a row and not in a cell...

import csv
import requests
from requests.auth import HTTPBasicAuth

requests.get('url', auth=HTTPBasicAuth('url', 'pass'))
a = requests.get('url2', auth=HTTPBasicAuth('url', 'pass'))

b = a.text
a = b.replace('"', '')
f = a.replace('%', '')
g = f.replace('.','')
z = g.replace(',', '.')
zz = z.replace(';',',')

with open('jj.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerows(zz)
>>> zz

Data:

Tuky,Fecha,Bid_requests,Bid_responses_won,Fill_rate,Bid_responses_won_clearing_price,Bid_responses_won_clearing_income,aaaP,17/01/2018,41325955,22453,0.05,3.97,89.17

This is my saved csv:

enter image description here

martineau
  • 119,623
  • 25
  • 170
  • 301
Martin Bouhier
  • 361
  • 2
  • 6
  • 19

2 Answers2

0

Use

with open('jj.csv', 'w') as out_file:
    writer = csv.writer(out_file)
    writer.writerows(zz.split(","))

This will create a list from your string, split at ',' - writerows takes an iterable and writes it into the file - a string is also iterable, thats why you gett each character seperately.

Read up on it here: https://docs.python.org/3/library/csv.html#writer-objects

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

try this:

import csv
import requests
from requests.auth import HTTPBasicAuth

requests.get('url', auth=HTTPBasicAuth('url', 'pass'))
a = requests.get('url2', auth=HTTPBasicAuth('url', 'pass'))

b = a.text
a = b.replace('"', '')
f = a.replace('%', '')
g = f.replace('.','')
z = g.replace(',', '.')
zz = z.replace(';',',')
zz = zz.split('.')

with open('jj.csv', 'w') as out_file:
    writer = csv.writer(out_file)
    writer.writerows([zz])

Explanation You need to pass a 2 dimensional array to write rows, in this case you only have one row so we pass [zz] to writer.writerows. zz itself should be an array where each element is a new column, which we achieve by doing zz.split('.')

shrumm
  • 151
  • 1
  • 6