使用Python 3中的编码打印到标准输出 [英] Printing to stdout with encoding in Python 3

查看:134
本文介绍了使用Python 3中的编码打印到标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python 3程序,该程序从Windows-1252编码的文件中读取一些字符串:

I have a Python 3 program that reads some strings from a Windows-1252 encoded file:

with open(file, 'r', encoding="cp1252") as file_with_strings:
    # save some strings

我以后要写到stdout。我试图做:

Which I later want to write to stdout. I've tried to do:

print(some_string)
# => UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 180: ordinal not in range(128)

print(some_string.decode("utf-8"))
# => AttributeError: 'str' object has no attribute 'decode'

sys.stdout.buffer.write(some_str)
# => TypeError: 'str' does not support the buffer interface

print(some_string.encode("cp1252").decode("utf-8"))
# => UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 180: invalid continuation byte

print(some_string.encode("cp1252"))
# => has the unfortunate result of printing b'<my string>' instead of just the string

I'我在这里挠头。我想打印从文件中获得的字符串,就像在cp1252中显示的一样。 (在我的终端中,当我执行更多$ file 时,这些字符显示为问号,因此我的终端可能是ascii。)

I'm scratching my head here. I'd like to print the string I got from the file just as it appears there, in cp1252. (In my terminal, when I do more $file, these characters appear as question marks, so my terminal is probably ascii.)

请澄清一下!谢谢!

推荐答案


使用cp1252编码时,必须使用相同的解码器。

When you encode with cp1252, you have to decode with the same.

例如:

import sys
txt = ("hi hello\n").encode("cp1252")
#print((txt).decode("cp1252"))
sys.stdout.buffer.write(txt)
sys.stdout.flush()

这将打印嗨 decodingn(在cp1252中编码)在解码后。

This will print "hi hello\n" (which was encoded in cp1252) after decoding it.

这篇关于使用Python 3中的编码打印到标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆