Python:解码文件中的base64多个字符串

标签 python

我是 python 的新手,我有一个这样的文件:

cw==ZA==YQ==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==dA==ZQ==cw==dA==

这是一个键盘输入,用base64编码,新的我想解码它 我通过代码在解码的第一个字符处停止来尝试这个。

import base64

file = "my_file.txt"
fin = open(file, "rb")
binary_data = fin.read()
fin.close()
b64_data = base64.b64decode(binary_data)
b64_fname = "original_b64.txt"
fout = open(b64_fname, "w")
fout.write(b64_data)
fout.close

欢迎任何帮助。谢谢

最佳答案

我假设您自己创建了测试输入字符串。

如果我将您的测试输入字符串分成 4 个字符的 block 并分别解码,我得到以下结果:

>>> import base64
>>> s = 'cw==ZA==YQ==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==YQ==cw==ZA==dA==ZQ==cw==dA=='
>>> ''.join(base64.b64decode(s[i:i+4]) for i in range(0, len(s), 4))

'sdadasdasdasdasdtest'

但是,您的测试字符串 sdadasdasdasdasdtest 的正确 base64 编码是:

>>> base64.b64encode('sdadasdasdasdasdtest')
'c2RhZGFzZGFzZGFzZGFzZHRlc3Q='

如果您将此字符串放在 my_file.txt 中(并重写您的代码以使其更简洁),那么一切正常。

import base64

with open("my_file.txt") as f, open("original_b64.txt", 'w') as g:
    encoded = f.read()
    decoded = base64.b64decode(encoded)
    g.write(decoded)

关于Python:解码文件中的base64多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28767484/

相关文章:

python - 子进程+多重处理-按顺序执行多个命令

python ttk TreeView : how to select and set focus on a row?

python - Pandas Dataframe 的子集,由具有特定列值的行组成

python - 使用Python获取https网站时超时

python - 如何制作对数最佳拟合线?

python - 如何将 feature_names_out 与 scikit 的 FunctionTransformer 一起使用

python - reshape Pandas 数据框分组变量

python scipy.stats pdf 和 expect 函数

python - Python中测试修改文件时间是否在2天内

python - 检查 pandas.Series.index 是否包含一个值