Is 'encoding is an invalid keyword' error inevitable in python 2.x?

后端 未结 4 1866
清酒与你
清酒与你 2020-12-08 00:21

Ansi to UTF-8 using python causing error

I tried the answer there to convert ansi to utf-8.

import io

with io.open(file_path_ansi, encoding=\'latin-         


        
相关标签:
4条回答
  • 2020-12-08 00:56

    For Python2.7, Use io.open() in both locations.

    import io
    import shutil
    
    with io.open('/etc/passwd', encoding='latin-1', errors='ignore') as source:
        with io.open('/tmp/goof', mode='w', encoding='utf-8') as target:
            shutil.copyfileobj(source, target)
    

    The above program runs without errors on my PC.

    0 讨论(0)
  • 2020-12-08 01:05

    TypeError: 'encoding' is an invalid keyword argument for this function

    open('textfile.txt', encoding='utf-16')
    

    Use io, it will work in both 2.7 and 3.6 python version

    import io
    io.open('textfile.txt', encoding='utf-16')
    
    0 讨论(0)
  • 2020-12-08 01:08

    This is how you can convert ansi to utf-8 in Python 2 (you just use normal file objects):

    with open(file_path_ansi, "r") as source:
        with open(file_path_utf8, "w") as target:
            target.write(source.read().decode("latin1").encode("utf8"))
    
    0 讨论(0)
  • 2020-12-08 01:10

    I had the same issue when I did try to write bytes to file. So my point is, bytes are already encoded. So when you use encoding keyword this leads to an error.

    0 讨论(0)
提交回复
热议问题