CSV檔案讀和寫
阿新 • • 發佈:2019-01-03
把資料儲存到CSV
CSV(Comma-Separated Values, 逗號分隔值)是儲存表哥資料的常用檔案格式
從零開始建立一個CSV檔案:
import csv
csvFile = open("../test.csv","w+")
try:
writer = csv.writer(csvFile)
writer.writerow(('number','number plus 2','number times 2'))
for i in range(10):
writer.writerow((i,i+2,i*2))
finally:
csvFile.close ()
Python新建檔案的機制考慮得非常周到,如果檔案不存在,Python會自動建立檔案(不會自動建立資料夾)。如果檔案已經存在,Python會用新的資料覆蓋之前的檔案
獲取HTML表格並寫入CSV檔案
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://xinsichen.com")
bsObj = BeautifulSoup(html,"lxml")
table = bsObj.findAll("table",{"class":"table table-striped table-bordered" })[0]
rows = table.findAll("tr")
csvFile = open("../editors.csv","wt",newline='',encoding='utf-8')
writer = csv.writer(csvFile)
try:
for row in rows:
csvRow = []
for cell in row.findAll(['td','th']):
csvRow.append(cell.get_text())
writer.writerow(csvRow)
finally :
csvFile.close()
讀取CSV
import csv
from io import StringIO
data = open("../editors.csv").read()
dataFile = StringIO(data)
csvReader = csv.reader(dataFile)
for row in csvReader:
print(row)