1、记录python读写csv文件,直接上代码
import csv header = ["学号","姓名","年龄"] values = [ ("1","zhangsan","19"), ("2","lisi","20"), ("3","wangwu","22"), ] def read_csv_file(): with open("test.csv","r",encoding="utf-8") as fp: # reader = csv.reader(fp) #使用列表的方式读取 reader = csv.DictReader(fp) #使用字典的方式读取 for x in reader: print(x) def write_csv_file(): with open("classroom.csv","w",encoding="utf-8",newline="") as fp: writer = csv.writer(fp) writer.writerow(header) writer.writerows(values) def write_csv_file_dic(): values = [ {"学号":100,"姓名":"高文祥","年龄":18}, {"学号":101,"姓名":"刘德华","年龄":28}, {"学号":102,"姓名":"李连杰","年龄":38} ] with open("classroom1.csv","w",encoding="utf-8",newline="") as fp: writer = csv.DictWriter(fp,header) writer.writeheader() writer.writerows(values) if __name__ == '__main__': write_csv_file_dic()