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

前端 未结 9 2050
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:16

    You opened the file in binary mode:

    with open(fname, 'rb') as f:
    

    This means that all data read from the file is returned as bytes objects, not str. You cannot then use a string in a containment test:

    if 'some-pattern' in tmp: continue
    

    You'd have to use a bytes object to test against tmp instead:

    if b'some-pattern' in tmp: continue
    

    or open the file as a textfile instead by replacing the 'rb' mode with 'r'.

提交回复
热议问题