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

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

    # -*- encoding: utf-8 -*-
    
    # converting a unknown formatting file in utf-8
    
    import codecs
    import commands
    
    file_location = "jumper.sub"
    file_encoding = commands.getoutput('file -b --mime-encoding %s' % file_location)
    
    file_stream = codecs.open(file_location, 'r', file_encoding)
    file_output = codecs.open(file_location+"b", 'w', 'utf-8')
    
    for l in file_stream:
        file_output.write(l)
    
    file_stream.close()
    file_output.close()
    

提交回复
热议问题