programing

TypeError: python 및 CSV에서 'str'이 아닌 바이트와 유사한 개체가 필요합니다.

goodjava 2022. 10. 31. 21:15

TypeError: python 및 CSV에서 'str'이 아닌 바이트와 유사한 개체가 필요합니다.

TypeError: 'str'이 아닌 바이트와 유사한 개체가 필요합니다.

HTML 테이블 데이터를 CSV 파일에 저장하기 위해 아래 python 코드를 실행하는 동안 위의 오류가 발생하였습니다.어떻게 올라타야 할지 모르겠어요.제발 도와주세요.

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 3 대신 Python 2 방법론을 사용하고 있습니다.

변경:

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

수신인:

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

다음과 같은 출력의 파일이 표시됩니다.

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에서는 바이너리 모드로 입력됩니다.

추가하도록 편집됨

실행한 코드는 다음과 같습니다.

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)

Python3에서도 같은 문제가 있었습니다.내 코드는 다음과 같이 쓰여 있었다.io.BytesIO().

로의 치환io.StringIO()해결된.

wb를 w로 변경하기만 하면 됩니다.

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

로.

outfile=open('./immates.csv','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()

저 같은 경우에는 BeautifulSoup을 사용하여 Python 3.x로 .txt를 작성했습니다.같은 문제가 있었습니다.@tsduteba가 말한 것처럼 첫 번째 줄의 wb를 w로 변경합니다.

언급URL : https://stackoverflow.com/questions/34283178/typeerror-a-bytes-like-object-is-required-not-str-in-python-and-csv