Python 无法理解如何读取utf-16文件并将其系统记录到utf-8
我试图获取一个UTF-16格式的文件,然后Python 无法理解如何读取utf-16文件并将其系统记录到utf-8,python,decoding,Python,Decoding,我试图获取一个UTF-16格式的文件,然后syslog以UTF-8格式将其输出到syslog服务器。我对python和编程相当陌生。 除了在syslog中没有以UTF-8的形式发送外,其他一切都正常 代码 import logging import logging.handlers import tailer import os import codecs logger = logging.getLogger('myLogger') logger.setLevel(logging.INFO)
syslog
以UTF-8格式将其输出到syslog
服务器。我对python和编程相当陌生。
除了在syslog
中没有以UTF-8的形式发送外,其他一切都正常
代码
import logging
import logging.handlers
import tailer
import os
import codecs
logger = logging.getLogger('myLogger')
logger.setLevel(logging.INFO)
#add handler to the logger
handler = logging.handlers.SysLogHandler(address=('x.x.x.x', 514))
#add formatter to the handler
formatter = logging.Formatter('')
handler.formatter = formatter
logger.addHandler(handler)
while True:
for line in tailer.follow(open('z:\\ERRORLOG')):
logger.info(str.decode('utf-8'), line)
最后我还尝试了下面的方法
打开文件时,只需使用附加参数
编码
。
简单的例子:
with open('utf-16.txt', 'r', encoding='utf-16') as fr:
with open('utf-8.txt', 'w', encoding='utf-8') as fw:
for line in fr:
fw.write(line)
就你而言:
while True:
with open('z:\\ERRORLOG', encoding='utf-16') as fr:
for line in tailer.follow(fr):
logger.info(line)
请格式化代码,使其可读。您使用的是Python 2还是Python 3?对不起,Scott。刚刚想出了如何在Spython 3之后正确添加它。这是从MS SQL错误日志中读取的,您可能应该在open函数中使用编码参数,而不是字符串的解码方法Hi nobby。谢谢你的回复。但是我不想再写第二个文件了。我想用另一种编码直接对其进行系统日志记录。如果我用新的编码创建一个新文件,那么它可能会导致其他问题。有没有办法使用logger.info部分的编码选项?@Rlourenco,我已经更新了答案。主要的一点是,如果在函数
open
中传递正确的编码名称,python将自行解码文件。谢谢Nobby。你的回答确实使我走上了正确的道路。然而,我没有得到正确的格式输出,但我找到了另一个解决我的问题的方法,所以谢谢你。
while True:
with open('z:\\ERRORLOG', encoding='utf-16') as fr:
for line in tailer.follow(fr):
logger.info(line)