{"id":1075,"hash":"ceca60fdc7120c3567a0ceeaaa5298c63ff2d7c8915f9ee09cfa3379231458b5","pattern":"TypeError: a bytes-like object is required, not &#39;str&#39; in python and CSV","full_message":"TypeError: a bytes-like object is required, not 'str'\n\nI'm getting the above error while executing the below python code to save the HTML table data in a CSV file. How do I get rid of that error?\n\nimport csv\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl='http://www.mapsofindia.com/districts-india/'\nresponse=requests.get(url)\nhtml=response.content\n\nsoup=BeautifulSoup(html,'html.parser')\ntable=soup.find('table', attrs={'class':'tableizer-table'})\nlist_of_rows=[]\nfor row in table.findAll('tr')[1:]:\n    list_of_cells=[]\n    for cell in row.findAll('td'):\n        list_of_cells.append(cell.text)\n    list_of_rows.append(list_of_cells)\noutfile=open('./immates.csv','wb')\nwriter=csv.writer(outfile)\nwriter.writerow([\"SNo\", \"States\", \"Dist\", \"Population\"])\nwriter.writerows(list_of_rows)","ecosystem":"pypi","package_name":"beautifulsoup","package_version":null,"solution":"You are using Python 2 methodology instead of Python 3.\n\nChange:\n\noutfile=open('./immates.csv','wb')\n\nTo:\n\noutfile=open('./immates.csv','w')\n\nand you will get a file with the following output:\n\nSNo,States,Dist,Population\n1,Andhra Pradesh,13,49378776\n2,Arunachal Pradesh,16,1382611\n3,Assam,27,31169272\n4,Bihar,38,103804637\n5,Chhattisgarh,19,25540196\n6,Goa,2,1457723\n7,Gujarat,26,60383628\n.....\n\nIn Python 3 csv takes the input in text mode, whereas in Python 2 it took it in binary mode.\n\nEdited to Add\n\nHere is the code I ran:\n\nurl='http://www.mapsofindia.com/districts-india/'\nhtml = urllib.request.urlopen(url).read()\nsoup = BeautifulSoup(html)\ntable=soup.find('table', attrs={'class':'tableizer-table'})\nlist_of_rows=[]\nfor row in table.findAll('tr')[1:]:\n    list_of_cells=[]\n    for cell in row.findAll('td'):\n        list_of_cells.append(cell.text)\n    list_of_rows.append(list_of_cells)\noutfile = open('./immates.csv','w')\nwriter=csv.writer(outfile)\nwriter.writerow(['SNo', 'States', 'Dist', 'Population'])\nwriter.writerows(list_of_rows)","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/34283178/typeerror-a-bytes-like-object-is-required-not-str-in-python-and-csv","votes":230,"created_at":"2026-04-19T04:52:18.510778+00:00","updated_at":"2026-04-19T04:52:18.510778+00:00"}