2

I am trying to download a .csv file and save it onto my computer. However when I run the script below, I am getting the error "Error: line contains NULL byte". What is it that I am doing wrong?

import csv
import urllib2

url = 'http://wildfire.alberta.ca/reports/activedd.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)

for row in cr:
    print row

3 Answers 3

3

The file you're trying to download is in UTF-16 format, and the CSV module is not designed for that. You need to decode it from UTF-16 into some other format. For example:

import csv
import codecs
import urllib2

url = 'http://wildfire.alberta.ca/reports/activedd.csv'
response = urllib2.urlopen(url)
cr = csv.reader([x.strip() for x in codecs.iterdecode(response, 'UTF-16')])

data = [x for x in cr]

# Manipulate the data here

# Now to save the CSV:
with open('outputfile.csv', 'wb') as output:
    writer = csv.writer(output)
    writer.writerows(data)

If you just need to download the file, and not manipulate it, there are better ways (see minitoto's answer).

This is an example, and the newlines have to be stripped manually for this to work properly, so I'm sure there's probably a better way, but that's the main issue

Sign up to request clarification or add additional context in comments.

4 Comments

@Rishav yes, my bad, copied my testing code in a run and wrote decode instead of iterdecode. I have fixed it now
Thank you!! one more thing, what would I do if I want to save the file on my pc?
the question was how to download, not how to print out
@minitoto Your suggestion is indeed better wrt. that, I didn't see the "Save it to my computer" and presumed it was just downloading to open at the time. Nevertheless, I will add a way to save the file onto the end of my soloution in case calculations or verification of the CSV need to be done first.
1

I guess the easiest way is to use urlretrieve:

import urllib

url = 'http://wildfire.alberta.ca/reports/activedd.csv'
urllib.urlretrieve(url, "activedd.csv")

1 Comment

don't forget to leave a comment if downvoting
-1

Here's what I've done. The lazy way.

import urllib2

url = 'http://wildfire.alberta.ca/reports/activedd.csv'
response = urllib2.urlopen(url)
with open('activeddData.csv','w') as csvFile:
    for line in response.readlines():
        csvFile.write(line)

3 Comments

don't forget to leave a comment if downvoting
with open('activeddData.csv','w') as csvFile in which part do you mention writing to file?
@Rishav for line in response.readlines(): iterates each line in response, and csvFile.write(line) writes each lines in a new file called 'activeddData.csv'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.