Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. #
  4. # Copyright (c) 2010 Doug Hellmann. All rights reserved.
  5. #
  6. """Errors decoding Unicode data.
  7. """
  8. #end_pymotw_header
  9.  
  10. import codecs
  11. import sys
  12.  
  13. from codecs_to_hex import to_hex
  14.  
  15. error_handling = sys.argv[1]
  16.  
  17. text = u'pi: \u03c0'
  18. print 'Original :', repr(text)
  19.  
  20. # Save the data with one encoding
  21. with codecs.open('decode_error.txt', 'w', encoding='utf-16') as f:
  22. f.write(text)
  23.  
  24. # Dump the bytes from the file
  25. with open('decode_error.txt', 'rb') as f:
  26. print 'File contents:', to_hex(f.read(), 1)
  27.  
  28. # Try to read the data with the wrong encoding
  29. with codecs.open('decode_error.txt', 'r',
  30. encoding='utf-8',
  31. errors=error_handling) as f:
  32. try:
  33. data = f.read()
  34. except UnicodeDecodeError, err:
  35. print 'ERROR:', err
  36. else:
  37. print 'Read :', repr(data)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement