我该如何在创建数据库输入(s1)、从中加载(s2)并将其正确格式化后传递回文件中,以便传输所有内容?
import time,os,sys,base64
s = "Hello World!\r\nHeyho"
#with s1 i make an input to the database; with s2 I select it -> works most time
s1 = base64.b64encode(s.encode("UTF-8")).decode("UTF-8") #print("Base64 Encoded:", s1)
s2 = base64.b64decode(s1.encode("UTF-8")).decode("UTF-8") #print(s2)
#example that I try to save it in a file:
s3 = "PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+"
with open("C:\\Users\\001\\Downloads\\Output.txt", "w") as text_file:
text_file.write("Ausgabe: %s" % base64.b64decode(s3.encode("UTF-8")).decode("UTF-8")) #with .encode('ascii', 'ignore') i whould delete the signs
日志:
C:\Users\001\Downloads>python trythis.py
Traceback (most recent call last):
File "trythis.py", line 11, in <module>
text_file.write("Ausgabe: %s" % base64.b64decode(s3.encode("UTF-8")).decode("UTF-8")) #with .encode('ascii', 'ignore') i whould delelte signs
File "C:\Users\001\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u25b7' in position 28: character maps to <undefined>
编辑:我正在使用Windows操作系统。
C:\Users\001\Downloads>python -V
Python 3.5.2
s1
和s2
只是为了演示未能正确解码数据的失败尝试而存在于代码中。只有s3
是相关的。UTF-8 解码是必要的,因为 Base64 编码的数据实际上是 UTF-8 编码的 HTML 页面的一部分。而且base64.b64decode()
返回一个bytes
对象。所以在这种情况下是必要的。 - wovano