TankorSmash
TankorSmash

Reputation: 12747

Unexpected end of archive

Hey there, I'm pretty new to programming and I've got a problem with the Python Challenge; and I've removed the exact url in hopes avoiding any heavy spoilers.

Anyway, my problem is that I'm trying to open the file I've created, in WinRAR after I've ran the following code, and it tells me the file has an "unexpected of end of archive". Naturally I've tried to rerun my code a few times just in case, and still no luck.

I've also grabbed the file with my browser from the same url to make sure that the file itself isn't damaged, and opened it without any errors, so I'm pretty stumped. I guess I'm missing some basic element of the process?

I appreciate your help in advance!

import urllib

url = "http://www.pythonchallenge.com/pc/def/xxxxxxx.zip"
site = urllib.urlopen(url)

newfile = open(url.split('/')[-1],'w')    

newfile.write(site.read())

site.close()
newfile.close()

Upvotes: 1

Views: 1311

Answers (1)

Thanatos
Thanatos

Reputation: 44256

I'm guessing you're on a Windows machine. (Mostly due to "WinRAR")

newfile = open(url.split('/')[-1],'w')

The 'w' opens the file for writing, but in "text" mode. In text mode, some OSs (like Windows) convert '\n' to something else ('\r\n' in Window's case.). To avoid this translation, open the file in binary mode 'b', with writing 'w': 'wb'

These letters derive from fopen. See the manual page for fopen, as I feel it has a better description of the flags than the Python docs. (Note however, that Python adds a few things to the flags.)

Upvotes: 3

Related Questions