Reading non-ASCII characters from a text file

前端 未结 3 1802
孤独总比滥情好
孤独总比滥情好 2021-01-06 00:03

I\'m using python 2.7. I\'ve tried many things like codecs but didn\'t work. How can I fix this.

myfile.txt

wörd

My code

         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-06 00:46

    import codecs
    #open it with utf-8 encoding 
    f=codecs.open("myfile.txt","r",encoding='utf-8')
    #read the file to unicode string
    sfile=f.read()
    
    #check the encoding type
    print type(file) #it's unicode
    
    #unicode should be encoded to standard string to display it properly
    print sfile.encode('utf-8')
    #check the type of encoded string
    
    print type(sfile.encode('utf-8'))
    

提交回复
热议问题