gpt4 book ai didi

Python base 64 解码 - 打印\n 而不是开始换行

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:13 25 4
gpt4 key购买 nike

我有 2 个 python 脚本,一个用于对文件进行 Base64 编码(这个可以正常工作),另一个用于对文件进行解码。

import base64
read_file = input('Name of file to read: ')
write_file = input('Name of file to write to: ')
image = open("%s"% read_file,'rb')
image_read = image.read()
image_64_encode = base64.encodestring(image_read)

raw_file = open("rawfile.txt","w")
raw_file.write("%s"% image_64_encode) #Write the base64 to a seperate text file
raw_file.close()

image_64_decode = base64.decodestring(image_64_encode)
image_result = open('%s'% write_file,'wb')
image_result.write(image_64_decode)
image_result.close()
image.close()

上面的脚本运行良好,并成功写入新文件(已解码)以及单独的 rawfile.txt,该文件显示为编码字符串。所以这一半的过程就很好了。

我有第二个python脚本来解码rawfile.txt,我可以打印rawfile的内容,但是当rawfile有新行时,python会打印

somerawfiletext\nmorerawfiletext

而不是想要的

somerawfiletext
morerawfiletext

这导致我收到 Base64 填充错误,因此无法解码。

第二个Python脚本:

import base64
rawfile = open("rawfile.txt",'r')
for line in rawfile:
print(line.rstrip())
decoded = base64.decodestring(rawfile)
print(decoded)

最佳答案

您可以更改第一个脚本以使用 b64encode 而不是 encodestring。这根本不包括换行符,那么您可以手动添加它。然后您将拥有一个可以使用换行符读取并解码的文件。所以我假设您的文件如下所示:

文件1.txt:

string1
string2
string3

现在,您可以使用简单的循环逐行编码并粘贴在列表中:

data = []
with open('file1.txt') as f:
for lines in f:
data.append(base64.b64encode(lines))

现在将该列表写入文件:

with open('encoded_file.txt', 'w') as f:
for vals in data:
f.write(vals + '\n')

现在读取该文件,解码并打印:

with open('encoded_file.txt') as f:
for vals in f.readlines():
print(base64.decodestring(vals))

您还可以将原始值存储在单独的列表中,并使用相同的方法保存到文件中,因此代替第一个循环,使用:

raw_data = []
data_to_encode = []
with open('file1.txt') as f:
for lines in f:
data_to_encode.append(base64.b64encode(lines))
raw_data.append(lines)

然后您将获得可以根据需要使用的原始数据和编码数据的列表。

关于Python base 64 解码 - 打印\n 而不是开始换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42575327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com