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

你可能感兴趣的:(工作相关)