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

Python base 64 decode-打印\n而不是开始换行,python,base64,Python,Base64,我有两个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.en

我有两个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
。这根本不包括换行符,然后您可以手动添加它。然后您将拥有一个文件,您可以使用换行符读入该文件并进行解码。所以我假设您的文件如下所示:

file1.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))
您还可以将原始VAL存储在单独的列表中,并使用相同的方法保存到文件中,因此使用以下方法代替第一个循环:

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)

然后您就有了一个原始数据和编码数据的列表,您可以随意使用。

谢谢,我回家后会尝试一下。:)