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

系统 2079 0

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

这种代码最少,最方便

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


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论