close

[Solved] Type: a bytes-like object is required, not ‘str’

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Type: a bytes-like object is required, not ‘str’ in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Type: a bytes-like object is required, not ‘str’ Error Occurs?

Today I get the following error Type: a bytes-like object is required, not ‘str’ in python.

How To Solve Type: a bytes-like object is required, not ‘str’ Error ?

  1. How To Solve Type: a bytes-like object is required, not 'str' Error ?

    To Solve Type: a bytes-like object is required, not 'str' Error I had the same issue with Python3. My code was writing into io.BytesIO().
    Replacing with io.StringIO() solved.

  2. Type: a bytes-like object is required, not 'str'

    To Solve Type: a bytes-like object is required, not 'str' Error I had the same issue with Python3. My code was writing into io.BytesIO().
    Replacing with io.StringIO() solved.

Solution 1


You are using Python 2 methodology instead of Python 3.

Change:

outfile=open('./immates.csv','wb')

To:

outfile=open('./immates.csv','w')

and you will get a file with the following output:

SNo,States,Dist,Population
1,Andhra Pradesh,13,49378776
2,Arunachal Pradesh,16,1382611
3,Assam,27,31169272
4,Bihar,38,103804637
5,Chhattisgarh,19,25540196
6,Goa,2,1457723
7,Gujarat,26,60383628
.....

In Python 3 csv takes the input in text mode, whereas in Python 2 it took it in binary mode.

Edited to Add

Here is the code I ran:

url='http://www.mapsofindia.com/districts-india/'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
table=soup.find('table', attrs={'class':'tableizer-table'})
list_of_rows=[]
for row in table.findAll('tr')[1:]:
    list_of_cells=[]
    for cell in row.findAll('td'):
        list_of_cells.append(cell.text)
    list_of_rows.append(list_of_cells)
outfile = open('./immates.csv','w')
writer=csv.writer(outfile)
writer.writerow(['SNo', 'States', 'Dist', 'Population'])
writer.writerows(list_of_rows)

Solution 2

I had the same issue with Python3. My code was writing into io.BytesIO().

Replacing with io.StringIO() solved.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read