Programing

TypeError : 파이썬과 CSV에서 'str'이 아닌 바이트와 같은 객체가 필요합니다.

lottogame 2020. 6. 25. 08:03
반응형

TypeError : 파이썬과 CSV에서 'str'이 아닌 바이트와 같은 객체가 필요합니다.


TypeError : 'str'이 아닌 바이트와 같은 객체가 필요합니다.

파이썬 코드 아래에서 실행하는 동안 HTML 테이블 데이터를 Csv 파일로 저장하는 동안 오류가 발생합니다. 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)

마지막 줄 위에.


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()해결 된 것으로 교체 .


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'로 변경하십시오.


just change wb to w

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

to

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

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

반응형