Python將base64轉為文件或者圖片

Hvnt3r發表於2018-08-23

有時候使用線上的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)

相關文章