0

I am trying to write unicode char in to text file using the following python code

with codecs.open("File.txt", mode='wb', encoding='utf-8') as f:
    f.write(str(u'\u6587\u5b66\u5b66\u58eb 2005\u5e743\u6708\uff1a \u83b7\u5927\u5b66\u82f1\u8bed\u516d\u7ea7\u8bc1\u4e66'))
    f.write('\n')
    f.close()

I am getting the following error

'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

Please help me in resolving this issue

Vigneshwaran
  • 782
  • 2
  • 7
  • 22

1 Answers1

1

If you are trying to write text, then you should probably open the file in text (and not binary) mode.

Change mode='wb' to mode='w' (if you want to create a new file or wipe clean an existing file) or mode='a' (if you want to append to an existing file):

with codecs.open("File.txt", mode='w', encoding='utf-8') as f:
    ...

In python 3.x you can just use open() instead of codecs.open(), like this:

with open("File.txt", mode='w', encoding='utf-8') as f:
    ...
Ralf
  • 16,086
  • 4
  • 44
  • 68