简体   繁体   中英

Trying to download data from URL with CSV File

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.

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)

It is probably because of your opening mode.

According to documentation :

'w' for only writing (an existing file with the same name will be erased)

You should use append( a ) mode to append it to the end of the file.

'a' opens the file for appending; any data written to the file is automatically added to the end.

Also, since the file you are trying to download is csv file, you don't need to convert it.

@albert had a great answer. I've gone ahead and converted it to the equivalent Python 2.x code. You were doing a bit too much work in your original program; since the file was already a csv you didn't need to do any special work to turn it into a csv.

import urllib2

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

response = urllib2.urlopen(url)
html = response.read()

with open('AusCentralbank.csv', 'wb') as f:
    f.write(html)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM