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})

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: