【发布时间】:2019-12-19 23:30:15
【问题描述】:
如何通过创建 db-input(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
【问题讨论】:
-
您在python3中编写了代码,并为shell放置了信息,该脚本应该与python3一起使用。但在 shell 中,您使用了 python(可能在 2.7 版中)。输入 shell/terminal/cmd
python,并在此处发布信息。 -
File "C:\Users\001\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py" 似乎表明作为写入过程的一部分,它试图采取您的字符串并将其编码为 cp1252 (windows ascii)。既然我看到很多来自 UTF-8 的不必要的编码/解码,你到底想做什么。 Python 3 已经在后台为您处理了大部分内容,因为默认情况下字符串是 unicode。
-
@WombatPM,没有“Windows ASCII”这样的东西。 ASCII 和 Windows-1252 是两种不同的字符编码。但你是对的。我假设
s1和s2只是在代码中,以演示正确解码数据的失败尝试。只有s3似乎相关。 UTF-8 解码是必要的,因为 Base64 编码的数据实际上是 UTF-8 编码的 HTML 页面的一部分。而base64.b64decode()返回一个bytes对象。所以在这种情况下是必要的。 -
谢谢,你是对的。 windows-1252 对应于代码页 1252,它由 ascii 字符集 + 西欧扩展 ascii 字符组成。它早于 unicode,本质上是在美国销售的许多基于 Windows 的工具和系统中的默认设置,这些工具和系统倾向于向最终用户隐藏复杂性。有趣的时间阅读i18nqa.com/debug/table-iso8859-1-vs-windows-1252.html 了解我们如何让 cp-1252、iso-8859-1、iso-8859-15、utf-8、utf-16 和 html 实体在您不知道的方面相似但不同直到很久以后才发现
标签: python encoding character-encoding python-unicode