0

I have a strange problem. A friend of mine sent me a text file. If I copy/paste the text and then paste it into my text editor and save it, the following code works. If I choose the option to save the file directly from the browser, the following code breaks. What's going on? Is it the browser's fault for saving invalid characters?

This is an example line.

When I save it, the line says

What�s going on?

When I copy/paste it, the line says

What’s going on?

This is the code:

import codecs
def do_stuff(filename):
 with codecs.open(filename, encoding='utf-8') as f:
 def process_line(line):
 return line.strip()
 lines = f.readlines()
 for line in lines:
 line = process_line(line)
 print line
do_stuff('stuff.txt')

This is the traceback I get:

Traceback (most recent call last):
 File "test-encoding.py", line 13, in <module>
 do_stuff('stuff.txt')
 File "test-encoding.py", line 8, in do_stuff
 lines = f.readlines()
 File "/home/somebody/.python/lib64/python2.7/codecs.py", line 679, in readlines
 return self.reader.readlines(sizehint)
 File "/home/somebody/.python/lib64/python2.7/codecs.py", line 588, in readlines
 data = self.read()
 File "/home/somebody/.python/lib64/python2.7/codecs.py", line 477, in read
 newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 4: invalid start byte

What can I do in such cases?

How can I distribute the script if I don't know what encoding the user who runs it will use?

Fixed:

codecs.open(filename, encoding='utf-8', errors='ignore') as f:
asked Jan 30, 2014 at 1:37

1 Answer 1

1

The "file-oriented" part of the browser works with raw bytes, not characters. The specific encoding used by the page should be specified either in the HTTP headers or in the HTML itself. You must use this encoding instead of assuming that you have UTF-8 data.

answered Jan 30, 2014 at 1:53
Sign up to request clarification or add additional context in comments.

1 Comment

The problem is that the the person who'll be running the program will be saving the file manually from various sources and I have no control over what the encoding is. I assumed that almost everything will be utf-8 but apparently I'm wrong. To him it's just "text" and won't understand encoding. What do I need to change in the code so that this doesn't happen?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.