파일을 작성하려고하는데 다음 오류가 발생합니다. TypeError : a bytes-like object is required, not 'str'
import requests, pandas
from bs4 import BeautifulSoup
r = requests.get("https://www.basketball-reference.com/players/a/")
c = r.content
soup = BeautifulSoup(c, "html.parser")
full_record_heading = soup.findAll("tr")
full_record = soup.findAll("tr")
playerdata = ""
playerdata_saved = ""
for record in full_record:
playerdata = ""
for player in record.findAll("td"):
playerdata = playerdata +","+player.text
playerdata_saved = playerdata_saved + playerdata[1:]+("\n")
# print(playerdata_saved)
header="From,To,Pos,Ht,Wt,Birth Date,College"
file=open("Basketball.csv","r+b")
file.write(header)
누구든지 오류의 이유를 말해 줄 수 있습니까? 사용 가능한 명령 및 문서의 올바른 구문을 어떻게 알 수 있습니까? 나는 파이썬을 처음 사용합니다.
파이썬에서 파일을 열 때 "파일 모드"(읽기 전용, 쓰기 전용, 읽기 및 쓰기, 파일이 바이너리 인 경우)를 지정해야합니다. 따라서이 줄에서 :
open("Basketball.csv","r+b")
파일을 READ-ONLY로 열고 파일을 BINARY로 읽도록 설정했습니다. 파일을 다음과 같이 열었어야합니다.
open("Basketball.csv","w")
쓰기 및 STRING
그럼에도 불구하고 CSV 파일을 수동으로 작성하고 있습니다. Pyhton에서는 그렇게 할 필요가 없습니다! 이 예를보십시오.
import requests
import pandas # Always import in different lines
from bs4 import BeautifulSoup
r = requests.get("https://www.basketball-reference.com/players/a/")
c = r.content
soup = BeautifulSoup(c, "html.parser")
full_record_heading = soup.findAll("tr")
full_record = soup.findAll("tr")
# Initialize your data buffer
my_data = []
# For each observation in your data source
for record in full_record:
# We extract a row of data
observation = record.findAll("td")
# Format the row as a dictionary - a "python hashmap"
dict_observation = {
"From": observation[0],
"To": observation[1],
"Pos": observation[2],
"Ht": observation[3],
"Wt": observation[4],
"Birth Date": observation[5],
"College": observation[6]
}
# Add the row to our DataFrame buffer
my_data.append(dict_observation)
# Now our DataFrame buffer contains all our data.
# We can format it as a Pandas DataFrame
dataframe = pandas.DataFrame().from_dict(my_data)
# Pandas DataFrames can be turned into CSVs seamlessly. Like:
dataframe.to_csv("Basketball.csv", index=False)
# Or even MS Excel:
dataframe.to_excel("Basketball.xlsx")
최대한 자주 파이썬 데이터 구조를 사용하십시오!
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다