I'm trying to make a function which prints to the command prompt and to a file. I get encoding/decoding errors with the following code:
import os
def pas(stringToProcess): #printAndSave
print stringToProcess
try: f = open('file', 'a')
except: f = open('file', 'wb')
print >> f, stringToProcess
f.close()
all = {u'title': u'Pi\xf1ata', u'albumname': u'New Clear War {EP}', u'artistname': u'Montgomery'}
pas(all['title'])
I get the following output:
Piñata
Traceback (most recent call last):
File "new.py", line 17, in <module>
pas(all['title'])
File "new.py", line 11, in pas
print >> f, stringToProcess
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 2: ordinal not in range(128)
I've tried all the encode()/decode() permutations I can imagine from similar answers on here, without success. How can this error be solved?