python - Python - Unicode 解码/编码
问题描述
如何通过创建 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>
编辑:我在窗户上工作。
C:\Users\001\Downloads>python -V
Python 3.5.2
解决方案
问题是您以文本模式打开文件,但未指定编码。在这种情况下,使用系统默认编码,在任何系统上都可能不同。
解决方案:指定open()encoding
的参数。
作为旁注:你为什么.decode('UTF-8')
?它确实有效,但由于数据是 Base64 编码的,我认为 ASCII 解码会更有意义。此外,您应该只在 I/O 二进制文件中进行编码/解码(因此在这种情况下是在写入文件时),尽管您可能只在这种情况下出于测试/演示目的而这样做。
更新:
显然,您的 Base64 编码数据也是 UTF-8 编码的(首先是 UTF-8,然后是 Base64),所以这就是为什么您需要先 Base64-decode 然后 UTF-8-decode 它。
以下是一个可移植的工作示例:
import base64
b64_encoded_text = 'PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+'
decoded_text = base64.b64decode(b64_encoded_text).decode('utf-8')
with open('Output.txt', 'wt', encoding='utf-8') as text_file:
text_file.write('Ausgabe: %s' % decoded_text)
尽管将原始二进制(UTF-8 编码)数据写入文件更容易:
import base64
b64_encoded_text = 'PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+'
with open('Output.txt', 'wb') as file:
# file.write(b'Ausgabe: ') # uncomment if really needed
file.write(base64.b64decode(b64_encoded_text))
推荐阅读
- android - 检查另一个类的 ToogleButton 的状态
- python - 将类继承作为参数
- jquery - 当 Web API 在我的所有 jquery 调用中停止工作时,会出现什么问题?
- google-apps-script - 参数 (number[]) 与 SpreadsheetApp.Range.setValues 的方法签名不匹配
- php - 如何在 php 7 中修复 SOAP-ERROR 解析 wsdl
- sql - 对 postgresql 的约束
- javascript - 在模式上获取重复数据后,我可以使用编辑操作删除重复数据吗?
- javascript - Node js和socket io——预约系统
- node.js - 在nodemailer的文本部分添加各种字段
- pycharm - PyCharm 运行配置不在主窗口上