不知道如何读取utf16文件并将其系统记录到utf8

2024-04-28 19:37:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取一个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)

#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)

i also tried the below at the end

while True:
for line in tailer.follow(open('z:\\ERRORLOG')):
    logger.info(str(line, 'utf-8'))

Tags: thetoimportaddformatterlogginghandlers格式
1条回答
网友
1楼 · 发布于 2024-04-28 19:37:12

打开文件时只需使用附加参数encoding。 简单示例:

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)

相关问题 更多 >