TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

前端 未结 9 2055
Happy的楠姐
Happy的楠姐 2020-11-22 04:58

I\'ve very recently migrated to Py 3.5. This code was working properly in Python 2.7:

with open(fname, \'rb\') as f:
    lines = [x.strip() for x in f.readli         


        
9条回答
  •  失恋的感觉
    2020-11-22 05:18

    I got this error when I was trying to convert a char (or string) to bytes, the code was something like this with Python 2.7:

    # -*- coding: utf-8 -*-
    print( bytes('ò') )
    

    This is the way of Python 2.7 when dealing with unicode chars.

    This won't work with Python 3.6, since bytes require an extra argument for encoding, but this can be little tricky, since different encoding may output different result:

    print( bytes('ò', 'iso_8859_1') ) # prints: b'\xf2'
    print( bytes('ò', 'utf-8') ) # prints: b'\xc3\xb2'
    

    In my case I had to use iso_8859_1 when encoding bytes in order to solve the issue.

    Hope this helps someone.

提交回复
热议问题