這裏有一個腳本,我使用的接收系統日誌,並將其附加到一個文本文件:Python腳本寫亂碼文件
# 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文件數據被轉換爲亂碼文本。任何想法爲什麼?在將套接字數據附加到文件之前,我應該做些什麼嗎?
謝謝。
什麼文本編輯器,你在查看文件? –
我正在查看它在記事本中。以下是我得到:ㄼ㈷䄾杵㈠<㐱㐺㨹㐱匠㕁〴嬠䥆䕒䅗䱌孝䥆䕒䅗䱌⁝晛物睥污嵬䰠䝏偟繸䕋孔剄偏⁝䤠㵎䅌⁎傳嘔匽䱅⁆剓㵃㤱⸲㘱⸸㠴㈮㘱䐠囈㈽㔵㈮㔵㈮㔵㈮㔵倠佒佔唽偄匠吶ㄽ㔷〰䐠吶ㄽ㔷〰㰀㜱㸲畁㤲ㄠ㨴ㄵ㌺<䅓㐵‰䙛剉坅䱁嵌䙛剉坅䱁嵌嬠楦敲慷汬⁝ – PCKING
嘗試不'STR()''左右data'。即打印>> myfile,數據 –