3

Possible Duplicate:
Setting the correct encoding when piping stdout in python

The following runs in the python shell (2.7.3) as expected

for i in range(999):
    print i, unichr(i)

saving it in a file (asd.py), and running in the shell

$ ./asd.py

works also, but

$ ./asd.py > asd.txt

gives:

Traceback (most recent call last):
  File "./asd.py", line 3, in <module>
    print i, unichr(i)
UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128)

Why is that? How to work around it?

2

1 Answer 1

2

Try this code,

#!/usr/bin/python
for i in range(999):
   print i, unichr(i).encode('utf-8')
Sign up to request clarification or add additional context in comments.

7 Comments

mmm? what's the difference?
@glglgl difference is .encode('utf-8')
it worked, but opening the file in gedit, it says: The file you opened has some invalid characters. If you continue editing this file you could corrupt this document., why is that ?
"$ iconv -f utf-8 asd.txt" try this command
@Ammar Sorry, I was blind. Didn't see it...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.