Unicode (UTF-8) reading and writing to files in Python

前端 未结 14 1220
谎友^
谎友^ 2020-11-22 17:10

I\'m having some brain failure in understanding reading and writing text to a file (Python 2.4).

# The string, which has an a-acute in it.
ss = u\'Capit\\xe1         


        
14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 17:31

    I was trying to parse iCal using Python 2.7.9:

    from icalendar import Calendar

    But I was getting:

     Traceback (most recent call last):
     File "ical.py", line 92, in parse
        print "{}".format(e[attr])
    UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 7: ordinal not in range(128)
    

    and it was fixed with just:

    print "{}".format(e[attr].encode("utf-8"))
    

    (Now it can print liké á böss.)

提交回复
热议问题