Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #1/usr/bin/env python
- # this is from The Python
- # Standard Library by example
- # ISBN13: 9780321767349
- import codecs
- import sys
- error_handling = sys.argv[1]
- text = u'pi: \u03c0'
- try:
- # Save the data, encoded as ASCII, using the error
- # handling mode specified on the command line.
- with codecs.open('encode_error.txt', 'w',
- encoding='ascii',
- errors=error_handling) as f:
- f.write(text)
- except UnicodeEncodeError, err:
- print 'ERROR:', err
- else:
- # If there was no error writing to the file.
- # show what it contains.
- with open('encode_error.txt', 'rb') as f:
- print 'File contents:', repr(f.read())
- """
- usage:
- $ python codecs_encode_error.py strict
- ERROR: 'ascii' codec can't encode character u'\u03c0'
- in position 4: ordinal not in range(128)
- $ python codecs_encode_error.py replace
- File contents: 'pi: ?'
- $ python codecs_encode_error.py ignore
- File contents: 'pi: '
- $ python codecs_encode_error.py xmlcharrefreplace
- File contents: 'pi: π'
- """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement