簡體   English   中英

如何使用csv_writer將列表寫到單獨的行中?

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

我使用BeautifulSoup提取了html表並將元素存儲在列表中。 接下來,我想將列表寫入.csv文件,但看來writerow函數不會將元素寫入不同的行中。

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()

.csv就像:

A,B,C,D,E

代替:

A,
B,
C,
D,
E,

我的代碼有什么問題? 我該如何解決? (我正在使用Python 2.7)

您可以使用此示例代碼

import csv
with open('test.csv', "wb") as f:
    writer = csv.writer(f)
    writer.writerow(['A'])
    writer.writerow(['B'])

這會給你這樣的結果

A
B

你可以傳遞你的價值

注意:請檢查站的類型,如果它返回的str將比單行中的值大,但是如果這是循環列表的示例代碼以將列表寫入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])
... 

您可以使用read_html從html獲取熊貓表,並使用to_csvsep='\\n'將其保存到csv文件中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM