Advertisement
rfmonk

codecs_bom_create.py

Jan 29th, 2014
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 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.  
  7. import codecs
  8. from codecs_to_hex import to_hex
  9.  
  10. # Pick the nonnative version of UTF-16 encoding
  11. if codecs.BOM_UTF16 == codecs.BOM_UTF16_BE:
  12.     bom = codecs.BOM_UTF16_LE
  13.     encoding = 'utf_16_le'
  14. else:
  15.     bom = codecs.BOM_UTF16_BE
  16.     encoding = 'utf_16_be'
  17.  
  18. print 'Native order     :', to_hex(codecs.BOM_UTF16, 2)
  19. print 'Selected order   :', to_hex(bom, 2)
  20.  
  21. # Encode the text.
  22. encoded_text = u'pi: \u03c0'.encode(encoding)
  23. print '{:14}: {}'.format(encoding, to_hex(encoded_text, 2))
  24.  
  25. with open('nonnative-encoded.txt', mode='wb') as f:
  26.     # Write the selected byte-order marker. It is not included
  27.     # in the encoded text because the byte order was given
  28.     # explicitly when selecting the encoding.
  29.     f.write(bom)
  30.     # Write the byte string for the encoded text.
  31.     f.write(encoded_text)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement