如何解码文件中base64格式的所有编码值?
下面是文件内容,其中编码的vaule以MTAu
开头,我需要解码它们。
SN: ols.com.,ptr=dc
PTR: ols.com
oncur: MTAuMTIzLjMzLjQ=
oncur: MTAuMTIzLjM1LjQ=
oncur: MTAuMzMuMzUuMTE0
SN: pls.com.,ptr=dc
PTR: pls.com
oncur: MTAuMTIzLjMzLjQ=
oncur: MTAuMTIzLjM1LjQ=
oncur: MTAuMzMuMzUuMTE0
SN: qls.com.,ptr=dc
PTR: qls.com
oncur: MTAuMTIzLjMzLjQ=
oncur: MTAuMTIzLjM1LjQ=
oncur: MTAuMzMuMzUuMTE0
我尝试了什么:
import base64
with open('testFile') as f:
for line in f:
if "MTAu" in line:
ln = base64.b64decode(line)
print(ln)
当我运行上面的代码时,它会给出类型错误:
Traceback (most recent call last):
File "decod4.py", line 7, in <module>
ln = base64.b64decode(line)
File "/usr/lib64/python2.6/base64.py", line 76, in b64decode
raise TypeError(msg)
TypeError: Incorrect padding
尝试使用命令行测试时,它可以工作:
>>> import base64
>>> line="MTAuMTIzLjMzLjQ="
>>> base64.b64decode(line)
b'10.123.33.4'
期望的输出:
SN: ols.com.,ptr=dc
PTR: ols.com
oncur: 10.123.33.4
oncur: 10.123.35.4
oncur: 10.123.33.114
SN: pls.com.,ptr=dc
PTR: pls.com
oncur: 10.123.33.4
oncur: 10.123.35.4
oncur: 10.123.33.114
任何帮助/方向将不胜感激。
答案 0 :(得分:3)
看起来你需要稍微清理一下这行,而你正试图解码整行而不仅仅是编码的字符串。试试这个:
with open('testFile') as f:
for line in f:
if 'MTAu' in line:
dec_str, enc_str = line.split(':')
ln = base64.b64decode(enc_str).decode()
print('{}: {}'.format(dec_str, ln))
else:
print(line.rstrip())