Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode and decode a mp3 file

Tags:

python

I want so save a mp3 file as encoded string in a text file, but it doesn't work with my code

import sys, base64

f = open(sys.argv[1], 'r')
b = base64.b64encode(f.read())
print sys.getsizeof(b)
f.close()

try:
    file = open(sys.argv[2] + '.txt', 'w')
    file.write(b)
    file.close()
except:
    print('Something went wrong!')
    sys.exit(0)

f = open(sys.argv[2] + '.txt', 'r').read()
b = base64.b64decode(f)
f.close()

try:
    file = open(sys.argv[2] + '2.mp3', 'w')
    file.write(b)
    file.close()
except:
    print('Something went wrong!')
    sys.exit(0)

The encoded string is too short for being the full string, so there isn't a good result. So why "doesn't" it work?

like image 372
Jon Lamer Avatar asked Sep 12 '25 11:09

Jon Lamer


1 Answers

Okay, I've reached my personal goal.

As pentadecagon has mentioned:

You need to call open using 'rb', because it's binary. Use len instead of sys.getsizeof.

f = open(sys.argv[2] + '.txt', 'r').read()
b = base64.b64decode(f)
f.close()

I changed this to

f = open(sys.argv[2] + '.txt', 'r')
b = base64.b64decode(f.read())
f.close()

So I've changed it and when I finally create the mp3 file again, you need to write binary 'wb' and it works.

like image 178
Jon Lamer Avatar answered Sep 15 '25 01:09

Jon Lamer