Reputation: 438
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?
Upvotes: 4
Views: 9126
Reputation: 438
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.
Upvotes: 6