![](/img/trans.png)
[英]Python: AttributeError: 'tuple' object has no attribute 'read'
[英]Python. How to fix error: “print tablecsv.read() AttributeError: 'tuple' object has no attribute 'read”
我選擇Python並嘗試為html表做解析器,然后我將不會創建.csv文件以將數據導入到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"
然后,我創建了csv文件並出現錯誤。
>>> 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
不幸的是,我無法理解何時以及如何創建元組。 當我弄錯了以及如何解決它時,有人可以向我解釋嗎?
您在這里錯過了方法名稱: tablecsv = (r'/tmp/table.csv', 'r')
即您可能想打開文件。 tablecsv = open(r'/tmp/table.csv', 'r')
您還應該在寫入后關閉文件,然后再使用tablecsv.close()
從文件中讀取
如果您僅在方括號中包含項目列表,例如(r'/tmp/table.csv', 'r')
則會創建一個元組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.