python 简单地从字符串或可读文件中解码base64内容

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 简单地从字符串或可读文件中解码base64内容相关的知识,希望对你有一定的参考价值。

#!/usr/bin/python

# Demo code. Decode base64 content from a string or a readable file
# Works for Python 2.7.3, at least 

# Usage
# decodebase64.py base64string
# decodebase64.py /absolute/path/to/base64/file

import sys
import os
import base64    

# testStr is for test usage, when they are assinged to the variable s to replace ''.
#testStr='Y29uZmlnLmpzb24ub2Jmc3Byb3h5LjIwMTYwMjIyXzE3NDcyOA=='
#testStr2='/path/to/base64/file'

def decodeStr(s):
    rslt=base64.b64decode(s)
    print 'Decoded result:\n',rslt


def decodeFile(fPath):
    f = open(fPath, 'r')  # better to use the with-as clause
    readed = [line.rstrip() for line in f]
    f.close()
    strReaded = ''.join(readed)
    print strReaded
    decodeStr(strReaded)

def main():
    print 'Args: ',str(sys.argv) 
    # s = testStr
    s = ''
    if len(sys.argv) > 1:
        s=sys.argv[1]

    if os.path.isabs(s):
        decodeFile(s)
    elif len(s) > 0:
        decodeStr(s)
    else:
        print "Nothing I can do"

main()

以上是关于python 简单地从字符串或可读文件中解码base64内容的主要内容,如果未能解决你的问题,请参考以下文章

Python SQL:存储对象或可迭代对象

bash命令

python之路3:文件操作和函数基础

在 Python 中,如何轻松地从一些源数据生成图像文件?

Python-文件操作

python第三天:字符编码文件操作函数