gpt4 book ai didi

Python 脚本将乱码写入文件

转载 作者:行者123 更新时间:2023-11-28 22:02:00 26 4
gpt4 key购买 nike

这是我用来接收系统日志并将其附加到文本文件的脚本:

# Receives packets on udp port 514 and
# writes to syslog.txt

from socket import *

# Set the socket parameters
host = "myhost"
port = 514
buf = 1024
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
data,addr = UDPSock.recvfrom(buf)
if not data:
print "Client has exited!"
break
else:
print "\nReceived message '", data,"'"

# This will create a new file or overwrite an existing file.
with open("C:\syslog.txt", "a") as myfile:
myfile.write(str(data))

# Close socket
UDPSock.close()

脚本工作正常,文本附加到文件。我看到了,而且读得很好。然而,当我关闭 python 时,txt 文件数据被转换为乱码文本。任何想法为什么?在将套接字数据附加到文件之前,我是否应该做其他事情?

谢谢。

最佳答案

您没有解析系统日志数据包。系统日志 is a protocol ;它不仅仅是纯文本。数据字符很可能会出现在您的文件中,这可能会触发某些自动字符检测。

关于Python 脚本将乱码写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12185501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com