爬蟲寫入csv txt 等檔案
阿新 • • 發佈:2018-12-14
1、嵌有字典列表----csv
1.1
def nestedlist2csv(data,file_path): with open(file_path, 'w+',encoding='utf-8') as f: #寫入檔案,出現編碼問題,可以改變目標檔案的編碼方式 w = csv.writer(f) filednames=['內容','評分','時間','商品資訊','可靠度','追加評論天數','追加內容'] w = csv.DictWriter(f,fieldnames=filednames) w.writeheader() for comment in comment_data: w.writerow({ '內容':comment['content'], '評分':comment['point'], '時間':comment['time'], '商品資訊':comment['sku_info'], '可靠度':comment['reliabiltiy'], '追加評論天數':comment['afterdays'], '追加內容':comment['replycontent'] })
1.2
def nestedlist2csv(data,file_path): with open(file_path, 'w+',encoding='utf-8',newline='') as f: #寫入檔案,出現編碼問題,可以改變目標檔案的編碼方式 w = csv.writer(f) w = csv.writer(f) fieldnames=comment_data[0].keys() # solve the problem to automatically write the header w.writerow(fieldnames) for row in comment_data: w.writerow(row.values())