1

I am writing one file :

 with open("test_%s.tem" %i, "w") as f1:
 ....
 f1.close()

I want to convert the encoding to UCS-2 little endian format. Is it possible to do this in open() or close() functions. Any ideas would help.

user741592
  • 875
  • 3
  • 10
  • 25
  • possible duplicate of: http://stackoverflow.com/questions/14488346/python-3-reading-ucs-2-be-file – Elisha May 12 '14 at 09:47

2 Answers2

2

In Python 3, according to documentation in :https://docs.python.org/3/library/functions.html#open
you can specify the encoding with the encoding parameter.

with open("test_%s.tem" %i, "w", encoding="utf16") as f1:
Elisha
  • 4,811
  • 4
  • 30
  • 46
  • I am using python 2.7. I tried using codecs. However it shows:UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) – user741592 May 12 '14 at 09:55
  • ascii values should be between `1` to `128`. you are trying to write `239` (0xef) – Elisha May 12 '14 at 09:58
1

On Python 2 you can use codecs.open with the encoding parameter.

If you use Python 3 just use the encoding parameter of open.

UCS-2 is a subset of UTF-16, so try to use 'UTF-16' as the parameter value.

Matthias
  • 12,873
  • 6
  • 42
  • 48