Advertisement
rfmonk

codecs_decode_error.py

Jan 29th, 2014
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. #1/usr/bin/env python
  2.  
  3. # this is from The Python
  4. # Standard Library by example
  5. # ISBN13: 9780321767349
  6. # usage: strict - ignore - replace
  7.  
  8. import codecs
  9. import sys
  10.  
  11. from codecs_to_hex import to_hex
  12.  
  13. error_handling = sys.argv[1]
  14.  
  15. text = u'pi: \u03c0'
  16. print 'Original     :', repr(text)
  17.  
  18. # Save the data with one encoding
  19. with codecs.open('decode_error.txt', 'w', encoding='utf-16') as f:
  20.     f.write(text)
  21.  
  22. # Dump the bytes from the file
  23. with open('decode_error.txt', 'rb') as f:
  24.     print 'File contents:', to_hex(f.read(), 1)
  25.  
  26. # Try to read the data with the wrong encoding
  27. with codecs.open('decode_error.txt', 'r',
  28.                  encoding='utf-8',
  29.                  errors=error_handling) as f:
  30.  
  31.     try:
  32.         data = f.read()
  33.     except UnicodeDecodeError, err:
  34.         print 'ERROR:', err
  35.     else:
  36.         print 'Read     :', repr(data)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement