Python UnicodeDecodeError

pbe*_*r13 7 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
Run Code Online (Sandbox Code Playgroud)

我已阅读其他帖子,并将编码设置为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) + ')')
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

你需要弄清楚tree.com使用的编码; 根据这篇文章,可以任何MS-DOS代码页.

您可以浏览每个MS-DOS编码 ; 其中大多数都在python标准库中有一个编解码器.我想尝试cp437cp500第一; 后者是我认为的cp1252的MS-DOS前身.

将编码传递给open():

myfile = open('tree.txt', encoding='cp437')
Run Code Online (Sandbox Code Playgroud)

你真的应该考虑使用os.walk()而不是使用tree.com这项任务,但它至少可以帮助你解决这些问题.