三种方式使用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)

这种代码最少,最方便

字典格式写法

data = {“URL”: [‘1’, 1, 1], “predict”: [‘2’, 2, 2], “score”: [‘3’, 3, 3]}
d = pd.DataFrame(data)
d.to_excel(“result.xlsx”, index=0)

如果
df = pd.DataFrame({‘A’:0})这样写,会报错
ValueError: If using all scalar values, you must pass an index

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值