Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add list of data to individual cells of CSV file

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.

like image 377
Hein de Wilde Avatar asked Sep 21 '25 04:09

Hein de Wilde


1 Answers

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)
like image 140
Martin Evans Avatar answered Sep 22 '25 16:09

Martin Evans