I used BeautifulSoup to extract a html table and store elements in a list. Next, I would like to write the list into a .csv file, but it looks like the writerow function doesn't write elements into different rows.
import csv
from bs4 import BeautifulSoup
# Grab first table (station table in html file)
def parse_station(html):
soup = BeautifulSoup(html)
s_table = soup.find_all('table')[1]
stations = []
for tr in s_table.find_all('tr')[1:]:
td = tr.find_all('td')[1]
td = td.get_text()
stations.append(td)
return stations
stations = parse_station(open('data.html').read())
with open('stations.csv', "wb") as f:
csv_writer = csv.writer(f)
csv_writer.writerow([stations])
f.close()
The .csv is like:
A,B,C,D,E
instead of:
A,
B,
C,
D,
E,
What's wrong with my code? How can I fix it? (I'm using Python 2.7)
you can use this sample code
import csv
with open('test.csv', "wb") as f:
writer = csv.writer(f)
writer.writerow(['A'])
writer.writerow(['B'])
this will give you result like this
A
B
you can pass your value
Note: check type of stations if this will return str than your value will be in single row but if this is list that loop over list sample code for writing list into CSV.
>>> list = [1,2,3,4,5]
>>> with open('test.csv', 'wb') as f:
... writer = csv.writer(f)
... for i in list:
... writer.writerow([i])
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.