python写⼊csv⽂件的⼏种⽅法总结-python写⼊数据到csv或
xlsx⽂件的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 ists(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")
python怎么读csv数据第三种,使⽤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)
<_excel("result_xlsx.xlsx", index=0)
<_csv("result_csv.csv", index=0)
这种代码最少,最⽅便
您可能感兴趣的⽂章:python3+selenium实现qq邮箱登陆并发送邮件功能python3+selenium实现126邮箱登陆并发送邮件功能实例分析python3实现并发访问⽔平切分表python⾃动查询12306余票并发送邮箱提醒脚本Python3实现并发检验代理池地址的⽅法python配置⽂件写⼊过程详解python config⽂件的读写操作⽰例python批量读取⽂件名并写⼊txt⽂件中Python3并发写⽂件与Python对⽐

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。