Как исправить ошибку UnicodeDecodeError при чтении файлов - PullRequest
0 голосов
/ 04 августа 2020

Итак, я пытаюсь прочитать определенную строку из файла, но каждый раз, когда я пытаюсь, я получаю ошибку декодирования Unicode, в которой говорится, что код c не может ее декодировать. Вот точная ошибка:

Traceback (most recent call last):
  File "/Users/myusername(changed for privacy)/Documents/Programming project/project.py", line 9, in <module>
    print(f.readline())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd2 in position 16: invalid continuation byte

Я также пробовал команды f.read с теми же результатами. Вот мой полный код:

score = 0
i = 1
lives = 2
password = "p4ssw0rd"
points = 0
f = open("Songs.docx", "r")
print(f.readline()) #where the error arises
playerName = input("Welcome to the game! Please enter your name: ")
print("Hi, " + playerName + "!")
while i < 3:
    passwordAttempt = input("Please enter the password to play: ")
    if passwordAttempt == password:
        print("Correct passcode")      print("**********************************************************")
        break
    else:
        i = i - 1
        print("Incorrect password. Please try again.")
print("So this is how the game works")
print("A random song will be chosen. You will be given the name of the artist and the first letter of the song name.")
print("You must try and guess the name of the song based off this.")
print("If you are correct on your first attempt, you get 3 points. If correct on your second try, you'll receive 1 point.")
print("If you are incorrect on your second try then it's game over. Try and score as many points as you can!")
wannaPlay = input("So, " + playerName + ", do you still wanna play? YES or NO (all uppercase) ")
if wannaPlay == "YES":
    pass
elif wannaPlay == "NO":
    print("Well this was a waste of time.")
    import sys
    sys.exit("farewell")
else:
    print("You didnt type YES or NO so you've gotta GO.")
    import sys
    sys.exit("Bye")
print("Just checking, just checking. Now lets get on with it.")
print("**************************************************************")

, чтобы уточнить, что это Python 3.8.2. Что я могу сделать, чтобы исправить эту ошибку? Также я новичок в использовании переполнения стека, извините, если я не использовал правильный формат. Я также использовал правильный отступ, но по какой-то причине он отображается здесь одним большим блоком

...