Python: Read write binary file using Python

Like other programming languages, you have to handle binary file specifically. It will not work if you just dump your content into a file as text mode, if it is a binary data. You have to assign binary mode on it.

Lets say you want to download a PDF file from a website, and want to save at your PC. Instead of "w" write mode, you have to use "wb" mode. Means write as binary mode. So the code will be.

localFile = open("my_pdf.pdf", 'wb')
localFile.write(pdf_content)
localFile.close()


Similarly while reading the binary file, just use "wb" to read a file. Anyway here I'm giving a code that will help you to download a PDF file from a website. You can use any link of .doc, .xls, .gif, .jpg or any type. Just call the function with your url, and file name.

from urllib2 import urlopen
def downloadPDF(url, outfile):
try:
webFile = urlopen(url)
localFile = open(outfile, 'wb')
localFile.write(webFile.read())
webFile.close()
localFile.close()
except IOError, e:
print "Download error"


Cheers,
Wolf.

Comments