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

前端 未结 14 1212
谎友^
谎友^ 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:27

    except for codecs.open(), one can uses io.open() to work with Python2 or Python3 to read / write unicode file

    example

    import io
    
    text = u'á'
    encoding = 'utf8'
    
    with io.open('data.txt', 'w', encoding=encoding, newline='\n') as fout:
        fout.write(text)
    
    with io.open('data.txt', 'r', encoding=encoding, newline='\n') as fin:
        text2 = fin.read()
    
    assert text == text2
    

提交回复
热议问题