写入CSV文件:ValueError:关闭文件的I / O操作

时间:2015-09-01 17:40:19

标签: python file csv beautifulsoup bs4

代码从卡中抓取一个单独的事件,但我一直收到此错误:

  

C:\ Python27 \ python.exe C:/ Users / James / PycharmProjects / scraperscrappy   /scrapy.py Traceback(最近一次调用最后一次):       File" C:/Users/James/PycharmProjects/scraperscrappy/scrapy.py" ;,第31行,in         writer.writerow(c)ValueError:关闭文件的I / O操作

我正在使用pyCharm。

流程以退出代码1结束 Python动态创建csv文件,但我也尝试在项目中创建一个csv文件,但我仍然得到相同的消息。我认为问题可能在于第31行的zip之后的字符串。任何帮助赞赏。

import csv
from urllib import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.gbgb.org.uk/resultsRace.aspx?id=1793467")
bsObj = BeautifulSoup(html)

one = bsObj.findAll("li", {"class": "first essential fin"})
two = bsObj.findAll("li", {"class": "essential greyhound"})

three = bsObj.findAll("li", {"class": "timeDistance"})
four = bsObj.findAll("li", {"class": "trap"})
five = bsObj.findAll("li", {"class": "sp"})
six = bsObj.findAll("li", {"class": "timeSec"})
seven = bsObj.findAll("li", {"class": "essential trainer"})
eight = bsObj.findAll("li", {"class": "first essential comment"})

firstessentialfin = [a.getText().strip() for a in one]
essentialgreyhound = [b.getText().strip() for b in two]
timeDistance = [c.getText().strip() for c in three]
trap = [d.getText().strip() for d in four]
sp = [e.getText().strip() for e in five]
timeSec = [f.getText().strip() for f in six]
essentialtrainer = [g.getText().strip() for g in seven]
firstessentialcomment = [h.getText().strip() for h in eight]

with open('dogfile.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile, delimiter=",")
for c in zip(firstessentialfin, essentialgreyhound, timeDistance,    trap,sp, timeSec, essentialtrainer,
         firstessentialcomment):
    writer.writerow(c)

1 个答案:

答案 0 :(得分:2)

问题在于缩进。将for循环移动到with上下文管理器主体:

with open('dogfile.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile, delimiter=",")
    for c in zip(firstessentialfin, essentialgreyhound, timeDistance,    trap,sp, timeSec, essentialtrainer, firstessentialcomment):
        writer.writerow(c)