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

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

    The following code will throw a TypeError: a bytes-like object is required, not 'str'.

    for line in lines:
        print(type(line))# 
        if 'substring' in line:
           print('success')
    

    The following code will work - you have to use the decode() function:

    for line in lines:
        line = line.decode()
        print(type(line))# 
        if 'substring' in line:
           print('success')
    

提交回复
热议问题