Search code examples
pythonunicodedecodepython-unicode

Python UnicodeDecodeError exception


txt = input("vilken textfil vill du använda?")
fil = open(txt,"r")

spelare=[]
resultat=[]
bästnamn=None
bästkast=0

for line in fil:

kolumn=line.split()
kolumn1=len(kolumn[1])
kolumn2=len(kolumn[2])
if len(kolumn)<5:
    mu=float(kolumn[1])
    sigma=float(kolumn[2])
    #print(mu,sigma)
    #kast=random.normalvariate(mu,sigma)
    #print(kast)

    for r in range(0,6):
        kast=random.normalvariate(mu,sigma)
        resultat.append(kast)

if max(resultat)>bästkast:
   bästkast=max(resultat)
   bästnamn=kolumn[0]

print("Segrare", bästnamn, "som stötte", bästkast, "meter")

When I running the program I get this error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 85: ordinal not in range(128)

What am I doing wrong?

Thank you so much and yes I have python 3. With the change as you sad to import the codecs, I now get another error insteed.

ValueError: max() arg is an empty sequence

What sholud I do? any suggestions?


Solution

  • You’re reading your file as though it were encoded in ASCII, but it’s not. Given the 0xc3 I would say it’s probably encoded in UTF-8.

    So, you need to open it with UTF-8 encoding:

    import codecs
    
    fil = codecs.open(txt, "r", "utf-8")
    

    This all assumes you’re using Python 3, in which strings are Unicode by default. Since you had no problem with non-ASCII identifiers, that seems like a safe assumption.