python|python csv实时一条一条插入且表头不重复问题
目录
- csv实时一条条插入且表头不重复
- 连续写入txt
- csv写入时指定表头
- 练习
csv实时一条条插入且表头不重复 1、主要就是在最开始插入的时候判断下表头或者表格是否有数据
2、用csv reader(然后主要写是a追加模式,读是r模式)
import csvwith open("111.csv","a",encoding='utf-8',newline="") as f:k = csv.writer(f, dialect="excel")with open("111.csv", "r", encoding='utf-8', newline="") as f:reader = csv.reader(f)if not [row for row in reader]:k.writerow(["标题", "链接", "喜欢"])k.writerow(list)else:k.writerow(list)
all_datas = [[1,2],[2,3],[1,2],[4,5]]for list1 in all_datas:with open(r"ablchange1.csv", 'a+', encoding='utf-8-sig', newline="") as f:k = csv.writer(f, dialect="excel")with open("ablchange1.csv", "r", encoding='utf-8-sig', newline="") as f:reader = csv.reader(f)if not [row for row in reader]:k.writerow(["a","b"])k.writerow(list1)else:k.writerow(list1)
连续写入txt
with open("111.txt","a") as f:for i in range(100000):f.write(str(i)+"\n")if i==9000:break
csv写入时指定表头
import csvwith open('names.csv', 'w') as csvfile:fieldnames = ['first_name', 'last_name']writer = csv.DictWriter(csvfile, fieldnames=fieldnames)writer.writeheader()writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
练习
with open('specific.csv', 'a', newline="") as csvfile:fieldnames = ['ebayno', "pov", "mpn", "ipn", "opn"]writer = csv.DictWriter(csvfile, fieldnames=fieldnames)writer.writeheader()
file = open("aces_less.csv","w" , newline="")writer = csv.DictWriter(file, fieldnames=["asin","state"])writer.writeheader()for i in range(len(qs)):print(qs[i])state = getDataById(qs[i])print("状态 = " + state + "\n")writer.writerow({"asin":qs[i], "state": state})
【python|python csv实时一条一条插入且表头不重复问题】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
推荐阅读
- Python|Python 3.x对.CSV数据按任意行、列读取的过程
- 免费监控Linux/Ubuntu上的Nginx实时指标
- 使用Python,Twisted和Django通过Android手机控制笔记本电脑
- 构建实时,多平台移动应用程序(使用Ionic Framework和Firebase的示例)
- python项目|tsne原理以及代码实现(学习笔记)
- python项目|python爬取疫情数据并存入excel中(包括国内各省份,全球,国内外历史疫情数据)代码可以直接运行
- python项目|全卷积神经网络(FCN)和卷积神经网络(CNN)的主要区别
- python项目|深入理解网络结构设计中的add操作和concatenate操作
- OpenCV教程(在iOS中使用MSER进行实时对象检测)
- Python|Python 作业代码合集(如何求平均值、最大值、最小值())