We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,275 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Encode and decode binary data with base64

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")
file.write(binaryfile)
file.close()

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

2
Contributors
1
Reply
2 Hours
Discussion Span
3 Years Ago
Last Updated
3
Views
X-Boy
Newbie Poster
1 post since Apr 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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()
fin.close()

# 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")
fout.write(b64_data)
fout.close

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

# decode base64 string to original binary sound object
mp3_data = base64.b64decode(b64_str)
bumsfeld
Nearly a Posting Virtuoso
1,495 posts since Jul 2005
Reputation Points: 409
Solved Threads: 235
Skill Endorsements: 1

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0703 seconds using 2.66MB