I am writing a program for counting the approximate number of words in the file and getting an error stating 'ascii' codec can't decode byte.
How can I eliminate this error?
Below is the traceback of above error:
Traceback (most recent call last):
File "/Users/NikolaMac/Desktop/alice.py", line 23, in <module>
contents = f_obj.read()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)"
Here is my code:
filename='alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
# Count the approximate number of words in the file.
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")