2014年10月22日 星期三

Python, Unicode, UTF-8, and str

For example:


tree = ET.ElementTree(file=temp_Path + 'netviewraw.xml')

for elem in tree.iter():
    if elem.text is not None:     #elem.text type is unicode
        elem.text.encode('utf8')  # encode to utf8
        cfg.append(elem.text.encode('utf8')) # cfg is a list
f = open(fn, 'w') # no need to set encoding='utf-8', because on python2.7, file read/write only support str

for text in cfg:
        f.write(text+ '\n') #
f.close()

沒有留言:

張貼留言