Python reading from a file and saving to utf-8

后端 未结 3 1853
情书的邮戳
情书的邮戳 2020-11-28 02:51

I\'m having problems reading from a file, processing its string and saving to an UTF-8 File.

Here is the code:

try:
    filehandle = open(filename,\"         


        
相关标签:
3条回答
  • 2020-11-28 03:13

    You can also get through it by the code below:

    file=open(completefilepath,'r',encoding='utf8',errors="ignore")
    file.read()
    
    0 讨论(0)
  • 2020-11-28 03:14

    Process text to and from Unicode at the I/O boundaries of your program using the codecs module:

    import codecs
    with codecs.open(filename, 'r', encoding='utf8') as f:
        text = f.read()
    # process Unicode text
    with codecs.open(filename, 'w', encoding='utf8') as f:
        f.write(text)
    

    Edit: The io module is now recommended instead of codecs and is compatible with Python 3's open syntax, and if using Python 3, you can just use open if you don't require Python 2 compatibility.

    import io
    with io.open(filename, 'r', encoding='utf8') as f:
        text = f.read()
    # process Unicode text
    with io.open(filename, 'w', encoding='utf8') as f:
        f.write(text)
    
    0 讨论(0)
  • 2020-11-28 03:26

    You can't do that using open. use codecs.

    when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:

    import codecs
    file = codecs.open('data.txt','w','utf-8')
    
    0 讨论(0)
提交回复
热议问题