Python UnicodeDecodeError

时间:2013-01-31 21:24:16

标签: python python-3.x

我正在编写一个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 个答案:

答案 0 :(得分:6)

您需要确定使用的编码tree.com;根据任何MS-DOS代码页的this post

你可以浏览每一个MS-DOS encodings;大多数人都有codec in the python standard library。我先试试cp437cp500;后者是我认为的cp1252的MS-DOS前身。

将编码传递给open()

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

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

答案 1 :(得分:0)

在这一行:

myfile = open('tree.txt')

您应该指定文件的编码。在Windows上尝试:

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