Dealing with accents on inputs for text files

548
5
Jump to solution
07-25-2012 05:19 PM
ZulyG
by
New Contributor
I am currently creating a textfile in which I would like to write the users input. it needs to be able to deal with characters that contain accents i.e."é". The file needs to be coded on utf-8
I have managed to copy into the text file using utf-8 coding by by using codecs. However, I am having a hard time figuring out how to do this given a users input?.. so far  i have something like this:


import codecs import sys   aninput = sys.argv[1]    textfile =  codecs.open("testfile","wt","utf-8") textfile.write(u"é") # this works  textfile.write(aninput) # this fails assuming that aninput = "é" textfile.close()



any ideas?
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
AlanRussian
New Contributor III
Hi, Zuly,

Try changing the line where you set aninput to this:

aninput = sys.argv[1].decode(sys.getfilesystemencoding())

View solution in original post

0 Kudos
5 Replies
AlanRussian
New Contributor III
Hi, Zuly,

Try changing the line where you set aninput to this:

aninput = sys.argv[1].decode(sys.getfilesystemencoding())
0 Kudos
ZulyG
by
New Contributor
Hi Alan,
I continue to get the following error:

<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
Failed to execute (Script).
0 Kudos
AlanRussian
New Contributor III
Hi Alan,
I continue to get the following error:

<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
Failed to execute (Script).


Does the following script not work for you?  It works fine for me, and if I remove the decode, I get the same error as you.

import codecs
import sys


aninput = sys.argv[1].decode(sys.getfilesystemencoding())


textfile =  codecs.open("testfile","w","utf-8")
textfile.write(aninput)
textfile.close()
0 Kudos
ZulyG
by
New Contributor
Does the following script not work for you?  It works fine for me, and if I remove the decode, I get the same error as you.

import codecs
import sys


aninput = sys.argv[1].decode(sys.getfilesystemencoding())


textfile =  codecs.open("testfile","w","utf-8")
textfile.write(aninput)
textfile.close()


Got it to work! 🙂 THANXS
the reason it would'nt work was because I was adding the following line:
"arcpy.AddMessage(str(aninput))"
0 Kudos
AlanRussian
New Contributor III
Got it to work! 🙂 THANXS
the reason it would'nt work was because I was adding the following line:
"arcpy.AddMessage(str(aninput))"


Fantastic!  Glad to hear.
0 Kudos