'write csv in one cell
I want to write the following script to write in one cell. Currently the script creates 2 columns, but I only want to write it in one cell. See below for the desired output format.
Code:
from bs4 import BeautifulSoup
import requests
import csv
URL = 'https://www.electrive.com/2022/02/20/byd-planning-model-3-like-800-volt-sedan-called-seal/'
(response := requests.get(URL)).raise_for_status()
soup = BeautifulSoup(response.text, 'lxml')
paragraphs = soup.find('section', class_='content').find_all('p')
# the sources in the last paragraph
sources = paragraphs[-1].find_all('a')
# put the sources name and link in a dict
sources_links = []
for source in sources:
sources_links.append(f"{source.text}({source['href']})")
# write in csv
with open('electrive_scrape_source.csv', 'w') as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['Source'])
csv_writer.writerow(sources_links)
Desired output in one csv cell - separated with a comma:
xchuxing.com (https://xchuxing.com/article/45850), cnevpost.com (https://cnevpost.com/2022/02/18/byd-seal-set-to-become-new-tesla-model-3-challenger/)
Solution 1:[1]
First to get the comma separated string we can use the 'some delimiter'.join function to combine everything in the list into a single string separated by that delimiter. For the delimiter you'd use either ',' or use ', ' if you would like to automatically add spaces after the commas.
Then secondly, because csv_writer.writerow expects a list (or some other iterable) we need to wrap our comma separated string in a list, thus creating a list that only has one item in it. Like so.
csv_writer.writerow( [ ', '.join(sources_links) ] )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
