本文實例為大家分享了三種方式使用python寫數據到csv或xlsx文件,供大家參考,具體內容如下
第一種:使用csv模塊,寫入到csv格式文件
# -*- coding: utf-8 -*- import csv with open("my.csv", "a", newline='') as f: writer = csv.writer(f) writer.writerow(["URL", "predict", "score"]) row = [['1', 1, 1], ['2', 2, 2], ['3', 3, 3]] for r in row: writer.writerow(r)
第二種:使用openpyxl模塊,寫入到xlsx格式文件
# -*- coding: utf-8 -*- import openpyxl as xl import os def write_excel_file(folder_path): result_path = os.path.join(folder_path, "my.xlsx") print(result_path) print('***** 開始寫入excel文件 ' + result_path + ' ***** \n') if os.path.exists(result_path): print('***** excel已存在,在表后添加數據 ' + result_path + ' ***** \n') workbook = xl.load_workbook(result_path) else: print('***** excel不存在,創建excel ' + result_path + ' ***** \n') workbook = xl.Workbook() workbook.save(result_path) sheet = workbook.active headers = ["URL", "predict", "score"] sheet.append(headers) result = [['1', 1, 1], ['2', 2, 2], ['3', 3, 3]] for data in result: sheet.append(data) workbook.save(result_path) print('***** 生成Excel文件 ' + result_path + ' ***** \n') if __name__ == '__main__': write_excel_file("D:\core\\")
第三種,使用pandas,可以寫入到csv或者xlsx格式文件
import pandas as pd result_list = [['1', 1, 1], ['2', 2, 2], ['3', 3, 3]] columns = ["URL", "predict", "score"] dt = pd.DataFrame(result_list, columns=columns) dt.to_excel("result_xlsx.xlsx", index=0) dt.to_csv("result_csv.csv", index=0)
這種代碼最少,最方便
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
