python寫入數(shù)據(jù)到csv或xlsx文件的3種方法
本文實(shí)例為大家分享了三種方式使用python寫數(shù)據(jù)到csv或xlsx文件,供大家參考,具體內(nèi)容如下
第一種:使用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已存在,在表后添加數(shù)據(jù) ' + result_path + ' ***** \n')
workbook = xl.load_workbook(result_path)
else:
print('***** excel不存在,創(chuàng)建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)
這種代碼最少,最方便
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)現(xiàn)矩陣轉(zhuǎn)置的幾種方法詳解
這篇文章主要介紹了Python實(shí)現(xiàn)矩陣轉(zhuǎn)置的幾種方法詳解,zip() 函數(shù)用于將可迭代的對象作為參數(shù),將對象中對應(yīng)的元素打包成一個(gè)個(gè)元組,然后返回由這些元組組成的對象,這樣做的好處是節(jié)約了不少的內(nèi)存,需要的朋友可以參考下2023-08-08
Python環(huán)境使用OpenCV檢測人臉實(shí)現(xiàn)教程
這篇文章主要介紹了Python環(huán)境使用OpenCV檢測人臉實(shí)現(xiàn)教程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
詳解Python中表達(dá)式i += x與i = i + x是否等價(jià)
這篇文章主要介紹了關(guān)于Python中表達(dá)式i += x與i = i + x是否等價(jià)的相關(guān)資料,文中通過示例代碼介紹的很詳細(xì),相信對大家具有一定的參考價(jià)值,有需要的朋友們下面來一起看看吧。2017-02-02
python實(shí)現(xiàn)計(jì)數(shù)排序與桶排序?qū)嵗a
這篇文章主要介紹了python計(jì)數(shù)排序與桶排序,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03

