[csv] TypeError : 파이썬과 CSV에서 ‘str’이 아닌 바이트와 유사한 객체가 필요합니다.

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

Csv 파일에 HTML 테이블 데이터를 저장하기 위해 Python 코드 아래에서 실행하는 동안 오류가 발생합니다. 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’로 변경하십시오.


답변

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


답변