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

前端 未结 9 2048
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:11

    Like it has been already mentioned, you are reading the file in binary mode and then creating a list of bytes. In your following for loop you are comparing string to bytes and that is where the code is failing.

    Decoding the bytes while adding to the list should work. The changed code should look as follows:

    with open(fname, 'rb') as f:
        lines = [x.decode('utf8').strip() for x in f.readlines()]
    

    The bytes type was introduced in Python 3 and that is why your code worked in Python 2. In Python 2 there was no data type for bytes:

    >>> s=bytes('hello')
    >>> type(s)
    
    

提交回复
热议问题