Python Unicode解码错误

8 投票
2 回答
7571 浏览
提问于 2025-04-17 14:22

我正在写一个Python程序,用来读取一个DOS树命令输出的文本文件。当我循环到第533次时,Eclipse报了一个错误:

Traceback (most recent call last):
  File "E:\Peter\Documents\Eclipse Workspace\MusicManagement\InputTest.py", line 24, in  <module>
    input = myfile.readline()
  File "C:\Python33\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 3551: character maps  to undefined

我看过其他帖子,发现把编码设置为latin-1并没有解决这个问题,因为它在另一个字符上返回了一个UnicodeDecodeError错误,尝试使用utf-8也是一样。

以下是代码:

import os
from Album import *

os.system("tree F:\\Music > tree.txt")

myfile = open('tree.txt')
myfile.readline()
myfile.readline()
myfile.readline()

albums = []
x = 0

while x < 533:
    if not input: break
    input = myfile.readline()
    if len(input) < 14:
        artist = input[4:-1]
    elif input[13] != '-':
        artist = input[4:-1]
    else:
        albums.append(Album(artist, input[15:-1], input[8:12]))
    x += 1

for x in albums:
    print(x.artist + ' - ' + x.title + ' (' + str(x.year) + ')')

2 个回答

1

在这一行:

myfile = open('tree.txt')

你需要指定文件的编码方式。在Windows系统上,可以试试:

myfile = open('tree.txt',encoding='cp1250')
9

你需要弄清楚 tree.com 使用了什么编码;根据这篇帖子,可能是任何一种 MS-DOS 的代码页。

你可以查看每一种MS-DOS 编码;大部分都有Python 标准库中的编码器。我建议你先试试 cp437cp500;后者我觉得是 cp1252 的前身。

把编码传给 open()

myfile = open('tree.txt', encoding='cp437')

不过,你真的应该考虑用 os.walk() 来代替 tree.com 来完成这个任务,这样至少可以避免处理这些问题。

撰写回答