tags:

views:

77

answers:

2
   file = open('unicode.txt', 'wb')

    for i in range(10):
        file.write(str(unichr(i) ))

What i would like to do is to print all of the Unicode values to a text file

A: 

You shouldn't need the str() call around unichr(i). Python unicode objects are printable.

This:

file = open('unicode.txt', 'wb')
for i in range(10):
    file.write(unichr(i))

Seems to work for me, it prints 0x0000, 0x0001, 0x0002, etc. to the text file.

Ryan
-1 `str()` is both unneeded AND unwanted. Using it will guarantee FAILURE for i >= 256. "Python unicode objects are printable " -- sometimes, depending on which objects, what platform, narrow/wide-unicode Python build, default encodings, fonts available, Python 2.x or 3.x, phase of moon, etc. On my set-up your code produces a 10-BYTE file containing `'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t'` ... If i == 128, the outcome for me is `UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128)`
John Machin
+1  A: 
somefile = codecs.open('unicode.txt', 'wb', someencoding)

for i in range(10):
    somefile.write(unichr(i))
Ignacio Vazquez-Abrams