编程语言
首页 > 编程语言> > python中csv的读取

python中csv的读取

作者:互联网

先创建商品列表,然后写入创建表头
再写入一段新的数据,将新的数据中的“;”
换成“|"进行分割

import csv

productList = [{
        "sku": 1,
        "name": "iphone 12 pro max",
        "price": 12999,
        "brand": "苹果"
    }, {
        "sku": 2,
        "name": "mate 40",
        "price": 7999,
        "brand": "华为"
    }, {
        "1sku": 3,
        "name": "vivo r9",
         "prbcxice": 3999,
        "brand": "vivo"
    }]

def write_csv_list(list):
    list_new = []
    print(list)
    for obj in list:
        list_new.append([obj["sku"],obj["name"],obj["price"],obj["brand"]])
    print(list_new)

    with open("data.csv",'w',encoding='utf8') as csvFile:
        writer = csv.writer(csvFile)
        writer.writerow(["sku","名字","价格","品牌"])
        writer.writerow(list_new)




def write_csv_dic(list):
    with open("data1.csv",'w',encoding='utf8',newline='') as csvFile:
        #存储csv,拿到writer对象
        writer = csv.DictWriter(csvFile,["sku",'name',"price","brand"])
        #writer.writeheader()
        writer.writerows(list)
write_csv_dic(productList)

with open('data1.csv','a',encoding='utf8',newline='') as csvFile:
    mywriter = csv.writer(csvFile)
    mywriter.writerow(["江苏省|淮安市|清江浦区"])
    mywriter.writerow(["山东省|青岛市|黄岛区"])
    mywriter.writerow(["湖南省|怀化市|鹤城区"])

csv.register_dialect("mydealect",delimiter = "|",quoting = csv.QUOTE_ALL)
with open('data1.csv','r',encoding='utf8') as csvFile:
    lines = csv.reader(csvFile)
    for i,v in enumerate(lines):
        print(v)
        if (i > 1):
            break
    newlines = csv.reader(csvFile,'mydealect')
    for each in newlines:
        print(each)

标签:sku,读取,python,brand,writer,list,csvFile,csv
来源: https://blog.csdn.net/csh2388827741/article/details/116894382