Python UnicodeDecodeError

I am writing a Python program to read in a DOS tree command output to a text document. When I reach the 533rd loop iteration, Eclipse gives an error:

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

I read other posts, and setting the encoding to Latin-1 does not fix this problem, as it returns UnicodeDecodeErrorfor another character the same with trying to use utf-8.

Below is the code:

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) + ')')
+5
source share
2 answers

You need to find out what encoding is tree.comused; in accordance with this message , which may contain any of the MS-DOS code pages.

MS-DOS; python. cp437 cp500; MS-DOS cp1252, .

open():

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

os.walk() tree.com , .

+5

:

myfile = open('tree.txt')

. Windows :

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

All Articles