我尝试base64编码python文件,然后将其插入到txt文件中我尝试了以下代码:
import base64
file = open('Python.py', 'r')
txt = open('New.txt', 'wb')
encoded = base64.b64encode(file).read()
txt.write(encoded)
txt.writelines(lines)
file.close()
txt.close()
返回的错误是TypeError:需要类似字节的对象,而不是' _io.TextIOWrapper'
答案 0 :(得分:2)
这是一个简短的Python 3程序,它将任何二进制文件编码为Base64。
#!/usr/bin/env python3
import base64
import sys
def main():
if len(sys.argv) != 2:
print('Encode a file with Base64\nUsage:\n%s filename' % sys.argv[0])
sys.exit()
fname = sys.argv[1]
with open(fname, 'rb') as f:
data = f.read()
with open(fname + 'b64', 'wb') as f:
f.write(base64.encodebytes(data))
if __name__ == '__main__':
main()
这是在输入自己的源代码(保存为UTF-8)时产生的结果。
IyEvdXNyL2Jpbi9lbnYgcHl0aG9uMwoKaW1wb3J0IGJhc2U2NAppbXBvcnQgc3lzCgpkZWYgbWFp
bigpOgogICAgaWYgbGVuKHN5cy5hcmd2KSAhPSAyOgogICAgICAgIHByaW50KCdFbmNvZGUgYSBm
aWxlIHdpdGggQmFzZTY0XG5Vc2FnZTpcbiVzIGZpbGVuYW1lJyAlIHN5cy5hcmd2WzBdKQogICAg
ICAgIHN5cy5leGl0KCkKCiAgICBmbmFtZSA9IHN5cy5hcmd2WzFdCiAgICB3aXRoIG9wZW4oZm5h
bWUsICdyYicpIGFzIGY6CiAgICAgICAgZGF0YSA9IGYucmVhZCgpCgogICAgd2l0aCBvcGVuKGZu
YW1lICsgJ2I2NCcsICd3YicpIGFzIGY6CiAgICAgICAgZi53cml0ZShiYXNlNjQuZW5jb2RlYnl0
ZXMoZGF0YSkpCgppZiBfX25hbWVfXyA9PSAnX19tYWluX18nOgogICAgbWFpbigpCg==
这里有一些反转过程的代码
import base64
with open('base64encode.pyb64', 'rb') as f:
data = f.read()
with open('newfile', 'wb') as f:
f.write(base64.decodebytes(data))
结果newfile
与base64encode.py