欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-06-11 08:10:47|栏目:Python代码|点击:

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

这种代码最少,最方便

上一篇:python 定时任务去检测服务器端口是否通的实例

栏    目:Python代码

下一篇:Python实现的HMacMD5加密算法示例

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

本文地址:http://www.codeinn.net/misctech/139834.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有