开发者

Python. How to fix error: "print tablecsv.read() AttributeError: 'tuple' object has no attribute 'read"

I lern Python and try to do parcer for html table and then I wont to create .csv file for import data into mySQL.

>>> htmlread = handlestatbydate.read()
>>> soup = BeautifulSoup("".join(htmlread))
>>> souptable = soup('tbody', limit=2)[1].findAll('tr')
>>> souptablestr = ''.join(str(t) for t in souptable)
>>> reclearbyonce =开发者_如何学运维 re.compile('</tr><tr>\n|^<tr>\n|</tr>$')
>>> recleartd = re.compile(r'</td>|<td.*?>')
>>> retdtd = re.compile('""| ')
>>> soupclearbyonce = reclearbyonce.sub('', souptablestr)
>>> soupcleartd = recleartd.sub('"', soupclearbyonce)
>>> souptdtd = retdtd.sub('","', soupcleartd)
>>> print souptdtd
"59","00059413","00059413","70000000001","2011-08-22","18:01:48","0:07","0.45"
"60","00059413","00059413","70000000002","2011-08-22","18:49:48","0:43","1.95"
"61","00059413","00059413","70000000003","2011-08-22","18:52:50","5:07","11.70"
"62","00059413","00059413","70000000003","2011-08-22","19:02:47","4:10","9.75"

Then, I create csv file and have error.

>>> tablecsv = file(r'/tmp/table.csv', 'w')
>>> tablecsv.write("".join(souptdtd))
>>> tablecsv = (r'/tmp/table.csv', 'r')
>>> print tablecsv.read()

    print tablecsv.read()
AttributeError: 'tuple' object has no attribute 'read

Unfortunately, I can't understad when and how I can create tuple. Could somebody explain me when I wrong and how to fix it?


You have missed the method name here: tablecsv = (r'/tmp/table.csv', 'r') i.e. you probably want to open the file .e.g tablecsv = open(r'/tmp/table.csv', 'r')

You should also close the file after writing before reading from it with tablecsv.close()

If you just have a list of items in brackets e.g. (r'/tmp/table.csv', 'r') then this creates a tuple.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜