在python中将表写入CSV文件

时间:2016-06-09 19:54:56

标签: python csv

我写了这段代码:

import urllib.request
import re
import csv

from bs4 import BeautifulSoup
stocklist = ['aapl','goog','fb','amzn','COP']
for stocklist in stocklist:
 optionsUrl = urllib.request.urlopen('http://finance.yahoo.com/q?s='+stocklist).read()
 soup = BeautifulSoup(optionsUrl)
 optionsTable = [
  [x.text for x in y.parent.contents]
   for y in soup.findAll('td', attrs={'class': 'yfnc_tabledata1','rtq_table': ''})
 ]
 print(optionsTable)
 length = len(optionsTable[0])
 with open('test.csv', 'w', newline='') as fp:
  a = csv.writer(fp, delimiter=',')
  for y in range(length):
   a.writerow([x[y] for x in optionsTable])

我正在尝试将输出写入csv文件,但我只能写出" COP"的库存信息,而不是其他4种库存的信息,打印输出正确的数字行虽然..但我怎么只得到一次头和数据5次。另外,在写入CSV时,如何添加名为Symbol的新列。 像这样的东西:

符号[['上一个关闭:'],['开放:',],['出价:'],[' ;问:'],[' 1y Target Est:',],[' Beta:'],['收益日期:' ],[" Day'范围:"],[' 52wk范围:'],['音量:',],[& #39; Avg Vol(3m):'],['市值:'],[' P / E(ttm):'],[&# 39; EPS(ttm):'],[' Div&收益率:'],['预测市盈率(1年):'],[' P / S(ttm):],['前红利日期:'],['年度EPS Est \ n(9月16日)\ n:'],['季度EPS Est \ n(Jun-16)\ n: '],['平均推荐*:'],[' PEG比率(预计5年):]]

这是输出:

[['Prev Close:', '98.94'], ['Open:', '98.50'], ['Bid:', '99.74 x 1500'], ['Ask:', '99.75 x 1400'], ['1y Target Est:', '124.90'], ['Beta:', '1.48679'], ['Earnings Date:', 'Jul 19 - Jul 25 (Est.)'], ["Day's Range:", '98.47 - 99.99'], ['52wk Range:', '89.47 - 132.97'], ['Volume:', '23,937,011'], ['Avg Vol (3m):', '38,273,600'], ['Market Cap:', '546.10B'], ['P/E (ttm):', '11.10'], ['EPS (ttm):', '8.98'], ['Div & Yield:', '2.28 (2.31%) '], ['Forward P/E (1 yr):', '10.95'], ['P/S (ttm):', '2.38'], ['Ex-Dividend Date:', '05-May-16'], ['Annual EPS Est\n                      (Sep-16)\n                    :', '8.28'], ['Quarterly EPS Est\n                      (Jun-16)\n                    :', '1.39'], ['Mean Recommendation*:', '1.8'], ['PEG Ratio (5 yr expected):', '1.29']]
[['Prev Close:', '728.28'], ['Open:', '723.71'], ['Bid:', '728.40 x 1300'], ['Ask:', '728.67 x 100'], ['1y Target Est:', '924.83'], ['Beta:', '1.032'], ['Next Earnings Date:', 'N/A'], ["Day's Range:", '722.34 - 729.54'], ['52wk Range:', '515.18 - 789.87'], ['Volume:', '837,958'], ['Avg Vol (3m):', '1,787,830'], ['Market Cap:', '500.30B'], ['P/E (ttm):', '29.65'], ['EPS (ttm):', '24.58'], ['Div & Yield:', 'N/A (N/A) '], ['Forward P/E (1 yr):', '18.37'], ['P/S (ttm):', '6.41'], ['Ex-Dividend Date:', 'N/A'], ['Annual EPS Est\n                      (Dec-16)\n                    :', '33.60'], ['Quarterly EPS Est\n                      (Jun-16)\n                    :', '8.06'], ['Mean Recommendation*:', '1.8'], ['PEG Ratio (5 yr expected):', '1.31']]
[['Prev Close:', '118.39'], ['Open:', '118.13'], ['Bid:', '118.60 x 300'], ['Ask:', '118.61 x 1900'], ['1y Target Est:', '142.87'], ['Beta:', '0.840485'], ['Earnings Date:', 'Jul 27 - Aug 1 (Est.)'], ["Day's Range:", '117.71 - 118.68'], ['52wk Range:', '72.00 - 121.08'], ['Volume:', '12,644,305'], ['Avg Vol (3m):', '25,848,800'], ['Market Cap:', '339.02B'], ['P/E (ttm):', '72.49'], ['EPS (ttm):', '1.64'], ['Div & Yield:', 'N/A (N/A) '], ['Forward P/E (1 yr):', '25.90'], ['P/S (ttm):', '17.13'], ['Ex-Dividend Date:', 'N/A'], ['Annual EPS Est\n                      (Dec-16)\n                    :', '3.56'], ['Quarterly EPS Est\n                      (Jun-16)\n                    :', '0.81'], ['Mean Recommendation*:', '1.7'], ['PEG Ratio (5 yr expected):', '0.96']]
[['Prev Close:', '726.64'], ['Open:', '723.10'], ['Bid:', '727.45 x 100'], ['Ask:', '727.59 x 100'], ['1y Target Est:', '800.92'], ['Beta:', '1.6465'], ['Earnings Date:', 'Jul 21 - Jul 25 (Est.)'], ["Day's Range:", '722.30 - 728.91'], ['52wk Range:', '422.64 - 731.50'], ['Volume:', '1,970,078'], ['Avg Vol (3m):', '3,982,600'], ['Market Cap:', '343.40B'], ['P/E (ttm):', '300.00'], ['EPS (ttm):', '2.43'], ['Div & Yield:', 'N/A (N/A) '], ['Forward P/E (1 yr):', '73.41'], ['P/S (ttm):', '3.02'], ['Ex-Dividend Date:', 'N/A'], ['Annual EPS Est\n                      (Dec-16)\n                    :', '5.38'], ['Quarterly EPS Est\n                      (Jun-16)\n                    :', '1.10'], ['Mean Recommendation*:', '1.8'], ['PEG Ratio (5 yr expected):', '2.43']]
[['Prev Close:', '47.49'], ['Open:', '46.72'], ['Bid:', '46.69 x 2900'], ['Ask:', '46.70 x 2700'], ['1y Target Est:', '51.23'], ['Beta:', '1.42252'], ['Earnings Date:', 'Jul 28 - Aug 1 (Est.)'], ["Day's Range:", '46.55 - 47.14'], ['52wk Range:', '31.05 - 64.24'], ['Volume:', '4,646,126'], ['Avg Vol (3m):', '9,070,990'], ['Market Cap:', '57.76B'], ['P/E (ttm):', 'N/A'], ['EPS (ttm):', '-4.98'], ['Div & Yield:', '1.98 (4.35%) '], ['Forward P/E (1 yr):', '150.64'], ['P/S (ttm):', '2.15'], ['Ex-Dividend Date:', '18-May-16'], ['Annual EPS Est\n                      (Dec-16)\n                    :', '-2.26'], ['Quarterly EPS Est\n                      (Jun-16)\n                    :', '-0.67'], ['Mean Recommendation*:', '2.5'], ['PEG Ratio (5 yr expected):', '0.38']]

谢谢

1 个答案:

答案 0 :(得分:0)

您需要做的第一件事就是收集列标题。你的标题有很多额外的空格,我们最后也不需要:。所以我们做了一些格式化和清理工作。

header = [re.sub(' +',' ',i[0][:-1].replace('\n', ' ')) for i in optionsTable[0]]

with open('test.csv', 'w') as fp:
   writer = csv.writer(fp, delimiter=',')
   writer.writerow(header)
   for row in optionsTable:
      writer.writerow([i[1] for i in row])