python 导入csv模块后的读写

import csv


#读 读出为列表
def csv_read(file_name):
    with open(file_name,encoding="utf8") as f:
        reader = csv.reader(f)
        for row in reader:
            print(row,end="")
#读2 读出为字典
def csv_dic_read(file_name):
    with open(file_name,encoding="utf8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            # print(row,type(row))
            print(row["name"],row["age"],row["phone"])

#以列表的方式写
def csv_writer(file_name,data):
    with open(file_name,"a",encoding="utf8") as f:
        wr= csv.writer(f)
        for row in data:
            wr.writerow(row)

#以字典的方式写
def csv_dic_writer(file_name,head,data):
    #注意要加newline="",要不然写出的内容有空行存在
    with open(file_name,"a",encoding="utf8",newline="") as f:
        wr = csv.DictWriter(f,head)
        #直接写
        wr.writerows(data)
        # #也可一行一行写
        # print(len(data))
        # for d in data:
        #     print(d)
        #     wr.writerow(d)


if __name__ == '__main__':
    file_name = r"C:\Users\Administrator\Desktop\students.csv"

    #读写以列表方式
    data = [["mike2",20,150290],["ema2",23,119]]
    csv_read(file_name)
    csv_writer(file_name,data)
    csv_read(file_name)

    # 读写以字典方式
    head = ["name","age","phone"]
    dic = [{"name":"aaa","age":"20","phone":"110"},{"name":"bbb","age":"30","phone":"20"}]
    csv_dic_read(file_name)
    csv_dic_writer(file_name,head,dic)
    csv_dic_read(file_name)

 

你可能感兴趣的:(python)