1,105,391 Community Members

Encode and decode binary data with base64

Member Avatar
Newbie Poster
1 post since Apr 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]

I new to Python and I'm trying to make this script work, I made this in php, but I'd like to know how to do it in python...

I'm trying to encode a file with base64 and then decode and write the binary data to a file.

import base64

binaryfile = open("original.mp3").read()

file = open("out.txt", "w")

base64.encode(open("out.txt"), open("out.b64", "w"))
base64.decode(open("out.b64"), open("out.mp3", "w"))

print "original:", repr(binaryfile)
print "encoded message:", repr(open("out.b64").read())
print "decoded message:", repr(open("out.txt").read())

raw_input("\nPress ENTER to exit")

can someone tell me what I'm doing wrong and tell me the proper way to do what I'm looking for

Member Avatar
Posting Virtuoso
1,537 posts since Jul 2005
Reputation Points: 399 [?]
Q&As Helped to Solve: 261 [?]
Skill Endorsements: 7 [?]

Here is example code:

import base64

# pick sound file you have in working directory
# or give full path
sound_file = "original.mp3"

# use mode = "rb" to read binary file
fin = open(sound_file, "rb")
binary_data = fin.read()

# encode binary to base64 string (printable)
b64_data = base64.b64encode(binary_data)

b64_fname = "original_b64.txt"
# save base64 string to given text file
fout = open(b64_fname, "w")

# read base64 string back in
fin = open(b64_fname, "r")
b64_str = fin.read()

# decode base64 string to original binary sound object
mp3_data = base64.b64decode(b64_str)
This article has been dead for over three months: Start a new discussion instead
Start New Discussion
View similar articles that have also been tagged: