简体   繁体   中英

How do I use csv_writer to write a list into separate rows?

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])
... 

You could pandas for get table from html with read_html and save it to csv file with to_csv and sep='\\n' in your case:

import pandas as pd
df_list = pd.read_html(your_html)
df = df_list[0]
df.to_csv('Your file', sep='\n')

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM