本文實(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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

