【问题标题】:While reading file on Python, I got a UnicodeDecodeError. What can I do to resolve this?在 Python 上读取文件时,我收到了 UnicodeDecodeError。我能做些什么来解决这个问题?
【发布时间】:2013-05-07 20:46:35
【问题描述】:

这是我自己的项目之一。这将在我正在玩的游戏(AssaultCube)中帮助其他人受益。其目的是分解日志文件,让用户更容易阅读。

我一直收到这个问题。有人知道怎么修这个东西吗?目前,我不打算编写/创建文件。我只想修复这个错误。

触发错误的行是一个空行(它在第 66346 行停止)。

这是我脚本的相关部分的样子:

log  =  open('/Users/Owner/Desktop/Exodus Logs/DIRTYLOGS/serverlog_20130430_00.15.21.txt', 'r')
for line in log:

例外是:

Traceback (most recent call last):
  File "C:\Users\Owner\Desktop\Exodus Logs\Log File Translater.py", line 159, in <module>
    main()
 File "C:\Users\Owner\Desktop\Exodus Logs\Log File Translater.py", line 7, in main
    for line in log:
  File "C:\Python32\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 3074: character maps to <undefined>

【问题讨论】:

  • 文件是什么编码的?
  • 奇怪的是,这似乎只有在我使用特定文件时才会发生。它也停在特定线路。
  • 你的windows默认编码是cp1252,但是文件没有使用那个编码。
  • @Bugboy1028 根据定义,您无法在 decoded 文件本身中找到编码。您始终必须在文件旁边记住它,或者为您的文件格式设计检测方案。
  • 你可以试试chardet猜编码

标签: python file-io python-3.x


【解决方案1】:

试试:

enc = 'utf-8'
log = open('/Users/Owner/Desktop/Exodus Logs/DIRTYLOGS/serverlog_20130430_00.15.21.txt', 'r', encoding=enc)

如果它不起作用,请尝试:

enc = 'utf-16'
log = open('/Users/Owner/Desktop/Exodus Logs/DIRTYLOGS/serverlog_20130430_00.15.21.txt', 'r', encoding=enc)

你也可以试试

enc = 'iso-8859-15'

也可以试试:

enc = 'cp437'

wich 已经很老了,但它在 0x81 处也有一个“ü”,它适合我在攻击立方体主页上找到的字符串“üßer”。

如果所有编码都错误,请尝试联系一些开发突击立方体的人或如评论中所述:看看https://pypi.python.org/pypi/chardet

【讨论】:

猜你喜欢
  • 2022-11-30
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
相关资源
最近更新 更多