You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何对格式化文本文件Base64编码后解码仍保留原格式

问题:Base64解码后无法保留原文件换行格式

原文件内容

__META__
Autore             myname@mycompany.com
Data               2011/09/29_11:37:00
Sorgente           Non applicabile
Layout             1.0.0
Copyright          MyCompany
Note               Standard_Build
__INFO__
Nome               PACKAGE-NAME
CodiceProduzione   PKG_CODE
Descrizione        Descriptiom
ChangeOwner        organizational.unit@mycompany.com
Vendor             sigla=IC nome=MyCompany-SD
__SOURCE__
#Server             oldserver.mycompany.com
Server             newserver.mycompany.com
__CONTENTS__
_dir_              dir=/opt/package/x uid=user gid=group mode=755 policy=nn
#_dir_              dir=/tmp  uid=user gid=group mode=755 policy=nn
_file_             file=/opt/package/x/file1 uid=user gid=group mode=600 policy=nn
_file_             file=/opt/package/x/file2 uid=user gid=group mode=755 policy=fv
_file_             file=/opt/package/x/file3 uid=user gid=group mode=755 policy=fv
__SCRIPT__
postinstall        scr=/opt/package/x/file1.sh 
__END__

原编解码代码

import base64

MetaFile = '/path/file.tx'

data = open(MetaFile, "r").read()
data_byte = data.encode("utf-8")
MetaFile_encode = base64.b64encode(data_byte)

MetaFile_decode = base64.b64decode(MetaFile_encode)

print(MetaFile_encode)
print(MetaFile_decode)

问题现象

编码过程正常,但解码后直接打印结果时,换行符以\n转义字符形式显示,而非实际换行,无法还原原文件的排版格式。

解决方案

原因分析

base64.b64decode()返回的是字节串(bytes类型),Python在打印字节串时,会将其中的控制字符(如换行符)转义显示,而非解析为实际格式。

修正后的代码

import base64

MetaFile = '/path/file.tx'

# 读取文件内容(推荐用with语句自动管理文件句柄)
with open(MetaFile, "r", encoding="utf-8") as f:
    data = f.read()

# 编码为Base64
data_byte = data.encode("utf-8")
metafile_encode = base64.b64encode(data_byte)

# 解码并转换为字符串
metafile_decode_bytes = base64.b64decode(metafile_encode)
metafile_decode_str = metafile_decode_bytes.decode("utf-8")

# 打印编码结果(字节串)
print(metafile_encode)
# 打印解码后的字符串,格式与原文件完全一致
print(metafile_decode_str)

# 若需保存解码后的文件,直接写入字符串即可
with open('/path/decoded_result.txt', 'w', encoding='utf-8') as f:
    f.write(metafile_decode_str)

关键要点

  1. 解码后必须调用.decode("utf-8")将字节串转换为字符串,此时换行符会被正确解析为实际换行。
  2. 使用with open语句操作文件更安全,避免因忘记关闭文件导致资源泄漏。
  3. 保存解码内容时,直接写入转换后的字符串,无需额外处理格式。

内容的提问来源于stack exchange,提问作者Mauro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 21:35:18