Welcome, guest | Sign In | My Account | Store | Cart

Encodes or decodes base64-encoded files. If the input or output file(s) are ommited standard input/output will be used.

The encoding direction is detected from the file name: for decoding save the script e.g. as encode64.py. For decoding create a symlink with decode in the name.

Python, 8 lines
1
2
3
4
5
6
7
8
#!/usr/bin/env python

import base64
import sys

encode_or_decode = 'encode' in sys.argv[0].lower() and base64.encode or 'decode' in sys.argv[0].lower() and base64.decode or (sys.stderr.write("Error: script name must contain 'encode' or 'decode'!\n") or sys.exit(-1))

encode_or_decode(len(sys.argv) > 1 and open(sys.argv[1]) or sys.stdin, len(sys.argv) > 2 and open(sys.argv[2],'w') or sys.stdout)

3 comments

James Mills 10 years, 8 months ago  # | flag

Can you break up the long lines? They aren't wrapping!

Sunjay Varma 10 years, 8 months ago  # | flag

Python is a very great language. Putting all your code on 2 or 4 lines really will not make a difference in Python. The only thing it will do is make your code harder to read and edit later on.

This code will be less error prone as well:

#!/usr/bin/env python

import base64
import sys

if 'encode' in sys.argv[0].lower():
    encode_or_decode = base64.encode 
elif 'decode' in sys.argv[0].lower():
    encode_or_decode = base64.decode
else:
    sys.stderr.write("Error: script name must contain 'encode' or 'decode'!\n")
    sys.exit(-1)

if len(sys.argv) > 1: # we have an input file!
    inputfile = open(sys.argv[1])
else:
    inputfile = sys.stdin

if len(sys.argv) > 2: # we have an output file!
    outputfile = open(sys.argv[2], 'w')
else:
    outputfile = sys.stdout
encode_or_decode(inputfile, outputfile)

With the now longer code, you can also add things like the ability to provide only an output file.

-Sunjay03

ccpizza (author) 10 years, 8 months ago  # | flag

Thanks Sunjay for brushing it up! I have to keep reminding myself that white space is the main element of design.

Created by ccpizza on Tue, 29 Mar 2011 (MIT)
Python recipes (4591)
ccpizza's recipes (18)

Required Modules

  • (none specified)

Other Information and Tasks