Python 将数据列表添加到CSV文件的各个单元格
我正在尝试将列表的内容添加到CSV文件中。首先,我使用BeautifulSoup在网页上搜索第一栏的内容。然后我再次使用BeautifulSoup来删除其余专栏的内容。我的代码是:Python 将数据列表添加到CSV文件的各个单元格,python,python-3.x,csv,beautifulsoup,Python,Python 3.x,Csv,Beautifulsoup,我正在尝试将列表的内容添加到CSV文件中。首先,我使用BeautifulSoup在网页上搜索第一栏的内容。然后我再次使用BeautifulSoup来删除其余专栏的内容。我的代码是: # Content first column playerName = soup.find('div', class_='font-16 fh-red').text # Content second column playerStats = [] for stat in s
# 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])
playerName已正确写入CSV文件。但是,整个playerStats列表将写入第二列我希望将单个列表元素写入CSV文件的第二列、第三列、第四列等。我如何才能做到这一点
只是为了澄清:我是以“a”模式打开文件的,因为我在Python代码前面编写了CSV文件的头。在调用
writerow()
时尝试将两个列表附加在一起,如下所示:
# 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)