脚本专栏 
首页 > 脚本专栏 > 浏览文章

python写入数据到csv或xlsx文件的3种方法

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

本文实例为大家分享了三种方式使用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)

这种代码最少,最方便

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:Python3从零开始搭建一个语音对话机器人的实现
下一篇:自定义django admin model表单提交的例子
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网