This topic seems to be covered a lot but I have not been able to solve it using any of the solution offered by the suggestion in other people's posts. So here goes, I'm trying to write a .txt file after reading it from a url as follows:
from urllib.request import urlopen
fileobj = urlopen("http://www.gutenberg.org/ebooks/42671.txt.utf-8")
file = open('book.txt', 'w')
for byteseq in fileobj:
line = byteseq.decode()
file.write(line)
file.close()
fileobj.close()
However, I kept on getting UnicodeEncodeError: 'ascii' codec can't encode character on IDLE when I try to print the stripped line. The following is the code:
def function1():
file = open('coba.txt', 'r')
for line in file:
print(line.strip())
file.close()
Calling function1() gives an error message as follows:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/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)
The confusing bit is that, when I use terminal and execute the .py file using python3 file_name.py, it does print the line.strip(), and so does executing idle3 from terminal. However, opening idle3 from the App folder and using Sublime Text Python 3 build will result in the same error messages.
I am beyond clueless as to what is actually happening. Any help would be greatly appreciated!