十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
這篇文章主要為大家展示了“python如何寫入數(shù)據(jù)到csv或xlsx文件”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“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)
以上是“python如何寫入數(shù)據(jù)到csv或xlsx文件”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!