Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to download data from URL with CSV File

Tags:

python

I'm slightly new to Python and have a question as to why the following code doesn't produce any output in the csv file. The code is as follows:

import csv
import urllib2

url = 'http://www.rba.gov.au/statistics/tables/csv/f17-yields.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)

for row in cr:
    with open("AusCentralbank.csv", "wb") as f:
        writer = csv.writer(f)
        writer.writerows(row)

Cheers.

Edit:

Brien and Albert solved the initial issue I had. However, I now have one further question. When I download the CSV File which I have listed above which is in "http://www.rba.gov.au/statistics/tables/#interest-rates" under Zero-coupon "Interest Rates - Analytical Series - 2009 to Current - F17" and is the F-17 Yields CSV I see that it has 5 workbooks and I actually just want to gather the data in the 5th Workbook. Is there a way I could do this? Cheers.

like image 649
Jojo Avatar asked Jan 23 '26 22:01

Jojo


1 Answers

I could only test my code using Python 3. However, the only diffence should be urllib2, hence I am using urllib.respose for opening the desired url.

The variable html is type bytes and can generally be written to a file in binary mode. Additionally, your source is a csv-file already, so there should be no need to convert it somehow:

#!/usr/bin/env python3
# coding: utf-8

import urllib

url = 'http://www.rba.gov.au/statistics/tables/csv/f17-yields.csv'

response = urllib.request.urlopen(url)
html = response.read()

with open('output.csv', 'wb') as f:
        f.write(html)
like image 93
albert Avatar answered Jan 26 '26 12:01

albert