TypeError: a bytes-like object is required, not #39;str#39; in python and CSV(TypeError:需要一个类似字节的对象,而不是 python 和 CSV 中的“str)
问题描述
TypeError: 需要一个类似字节的对象,而不是 'str'
TypeError: a bytes-like object is required, not 'str'
在执行以下 python 代码以将 HTML 表数据保存在 Csv 文件中时出现上述错误.不知道怎么搭车.请帮帮我.
getting above error while Executing below python code to save the HTML table data in Csv file. don't know how to get rideup.pls help me.
import csv
import requests
from bs4 import BeautifulSoup
url='http://www.mapsofindia.com/districts-india/'
response=requests.get(url)
html=response.content
soup=BeautifulSoup(html,'html.parser')
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','wb')
writer=csv.writer(outfile)
writer.writerow(["SNo", "States", "Dist", "Population"])
writer.writerows(list_of_rows)
在最后一行的上方.
推荐答案
您使用的是 Python 2 方法而不是 Python 3.
You are using Python 2 methodology instead of Python 3.
变化:
outfile=open('./immates.csv','wb')
收件人:
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
.....
在 Python 3 中,csv 采用文本模式输入,而在 Python 2 中采用二进制模式.
In Python 3 csv takes the input in text mode, whereas in Python 2 it took it in binary mode.
编辑添加
这是我运行的代码:
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)
这篇关于TypeError:需要一个类似字节的对象,而不是 python 和 CSV 中的“str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TypeError:需要一个类似字节的对象,而不是 python 和 CSV 中的“str"


- python-m http.server 443--使用SSL? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 沿轴计算直方图 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01