简体   繁体   English

类型错误:需要一个类似字节的对象,而不是 python 和 CSV 中的“str”

[英]TypeError: a bytes-like object is required, not 'str' in python and CSV

TypeError: a bytes-like object is required, not 'str'类型错误:需要类似字节的对象,而不是“str”

getting above error while Executing below python code to save the HTML table data in Csv file.在执行以下 python 代码以将 HTML 表数据保存在 Csv 文件中时出现上述错误。 don't know how to get rideup.pls help me.不知道如何获得rideup.pls帮助我。

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)

on above the last line.在最后一行的上方。

You are using Python 2 methodology instead of Python 3.您正在使用 Python 2 方法而不是 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.在 Python 3 中 csv 以文本模式接受输入,而在 Python 2 中以二进制模式接受输入。

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)

I had the same issue with Python3.我在 Python3 上遇到了同样的问题。 My code was writing into io.BytesIO() .我的代码正在写入io.BytesIO()

Replacing with io.StringIO() solved.替换为io.StringIO()解决了。

just change wb to w只需将 wb 更改为 w

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

to

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

You are opening the csv file in binary mode, it should be 'w'您正在以二进制模式打开 csv 文件,它应该是'w'

import csv

# open csv file in write mode with utf-8 encoding
with open('output.csv','w',encoding='utf-8',newline='')as w:
    fieldnames = ["SNo", "States", "Dist", "Population"]
    writer = csv.DictWriter(w, fieldnames=fieldnames)
    # write list of dicts
    writer.writerows(list_of_dicts) #writerow(dict) if write one row at time
file = open('parsed_data.txt', 'w')
for link in soup.findAll('a', attrs={'href': re.compile("^http")}): print (link)
soup_link = str(link)
print (soup_link)
file.write(soup_link)
file.flush()
file.close()

In my case, I used BeautifulSoup to write a .txt with Python 3.x.就我而言,我使用 BeautifulSoup 用 Python 3.x 编写了一个 .txt。 It had the same issue.它有同样的问题。 Just as @tsduteba said, change the 'wb' in the first line to 'w'.正如@tsduteba 所说,将第一行中的“wb”更改为“w”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeError:需要一个类似字节的对象,而不是“str” - TypeError: a bytes-like object is required, not 'str' TypeError:需要类似字节的 object,而不是“str”? - TypeError: a bytes-like object is required, not 'str'? 需要一个类似字节的对象,而不是'str':TypeError - a bytes-like object is required, not 'str' : TypeError TypeError:需要一个类似字节的对象,而不是'str' - TypeError: a bytes-like object is required, not 'str' TypeError:需要一个类似字节的对象,而不是'str'python - TypeError: a bytes-like object is required, not 'str' python TypeError:需要一个类似字节的对象,而不是 Python 中 Image 命令的“str” - TypeError: a bytes-like object is required, not 'str' for Image command in Python Python TypeError:需要一个类似字节的对象,而不是'str' - Python TypeError: a bytes-like object is required, not 'str' TypeError:需要一个类似字节的对象,而不是'str'python3 - TypeError: a bytes-like object is required, not 'str' python3 类型错误:需要类似字节的 object,而不是使用子进程 python 的“str” - TypeError: a bytes-like object is required, not 'str' using Subprocess python TypeError:需要一个类似字节的对象,对于无服务器和Python3来说不是'str' - TypeError: a bytes-like object is required, not 'str' with serverless and Python3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM