python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > csv实时一条条插入且表头不重复

python csv实时一条一条插入且表头不重复问题

作者:loong_XL

这篇文章主要介绍了python csv实时一条一条插入且表头不重复问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

csv实时一条条插入且表头不重复

1、主要就是在最开始插入的时候判断下表头或者表格是否有数据

2、用csv reader(然后主要写是a追加模式,读是r模式)

import csv
with 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 csv
with 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})

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文