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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-04-03 我要评论

第一种:使用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)

这种代码最少,最方便

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们