I am trying to add the contents of a list to a CSV file. First I used BeautifulSoup to scrape the webpage for the content of the first column. Then I used BeautifulSoup again to scrape the content of the rest of the columns. My code is:
# Content first column
playerName = soup.find('div', class_='font-16 fh-red').text
# Content second column
playerStats = []
for stat in soup.find_all('span', class_='player-stat-value'):
playerStats.append(stat.text)
# Write name and stats to CSV file
with open('players.csv', 'a') as csvfile:
dataWriter = csv.writer(csvfile)
dataWriter.writerow([playerName, playerStats])
The playerName is written to the CSV file correctly. However, the entire playerStats list is written to the second column. I want the individual list elements to be written to the second, third, fourth etc. column of the CSV file. How can I do this?
Just for clarification: I am opening the file in the 'a' mode, because I wrote the header of the CSV file earlier in the Python code.
Try appending your two lists together when calling writerow()
as follows:
# Content first column
playerName = soup.find('div', class_='font-16 fh-red').text
# Content second column
playerStats = []
for stat in soup.find_all('span', class_='player-stat-value'):
playerStats.append(stat.text)
# Write name and stats to CSV file
with open('players.csv', 'a') as csvfile:
dataWriter = csv.writer(csvfile)
dataWriter.writerow([playerName] + playerStats)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With