Python将base64转为文档或者图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/levones/article/details/81983088

有时候使用在线的base64解码遇到一些大文件或者编码比较复杂的可能会出现一些问题,就写了个脚本来解决
gist地址:https://gist.github.com/Hvnt3r/dad413128496cea8b4e4f66757b8e8c3

#!/usr/bin/python2
# -*- coding: utf-8 -*-
'''
 将base码转换为文件的脚本,可以解码图片
 Author:Hvnt3r
 Date:2018.8.22
'''
import base64
#import codecs #解码其他编码格式如GBK需要的模块

file_path="E:/TMP/Python_test/one/"   # 定义文件所在的文件夹
raw_file_name="base64.txt"            # 定义存放base64的文件名
decoded_file_name="decoded_file.doc"  # 定义转换后的文件名,包括后缀

FILE_PATH=file_path+raw_file_name
def base_to_file(FILE):
    base64String = ""

    #1.从文件中读取base64并解码
    #with codecs.open(FILE, 'r', 'gbk') as f:   # 读取其他编码的文件
    with open(FILE, 'rb') as file:   # 将文件路径和文件名改成自己需要的
        for line in file.readlines():  #  去除每一行之后的换行符
            base64String += line.strip()

    #2.从粘贴的字符串中解码
    #raw_base64String = "在这里粘贴待转换的base64字符串"
    #for line in raw_base64String.rstrip("\n"):   # 去除每一行之后的换行符
    #    base64String+=line.strip()

    #写入文件
    with open(decoded_file_name, 'wb') as f:
        f.write(base64.b64decode(base64String))
        print "解码完毕"

if __name__ == "__main__":
    base_to_file(FILE_PATH)

猜你喜欢

转载自blog.csdn.net/levones/article/details/81983088