import csv # csv数据读取 rf = open('test.csv') reader = csv.reader(rf) line = reader.__next__() # 读取单行数据,并以列表的形式获取 print(line) # 结果如下: # ['商品编号', '商品名称', '单价', '上月末库存', '本月购进数量', '本月销售数量', '本月库存金额'] print(line[0], line[1]) # 可以直接通过列表的操作直接操作行内的数据 # 结果如下: # 商品编号 商品名称 # 遍历csv数据 for row in reader: print(row) # 结果如下: # ['1030101', '商品1', '600', '10', '123', '100', ''] # ['1030102', '商品2', '700', '60', '121', '100', ''] # ['1030103', '商品3', '60', '50', '122', '90', ''] # ['1030104', '商品4', '500', '12', '143', '125', ''] # ['1030105', '商品5', '80', '23', '89', '90', ''] # ['1030106', '商品6', '80', '5', '89', '90', ''] # ['1030107', '商品7', '90', '3', '90', '69', ''] # ['1030108', '商品8', '90', '40', '675', '599', ''] # ['1030109', '商品9', '50', '8', '56', '55', ''] # ['1030110', '商品10', '60', '18', '98', '97', ''] # ['1030111', '商品11', '50', '20', '65', '68', ''] # ['1030112', '商品12', '602', '22', '45', '44', ''] # ['1030113', '商品13', '800', '23', '22', '23', ''] # ['1030114', '商品14', '456', '21', '20', '10', ''] # ['1030115', '商品15', '54', '20', '65', '23', ''] # csv数据写入 wf = open('test_copy.csv', 'w') writer = csv.writer(wf) writer.writerow(['商品编号', '商品名称', '单价', '上月末库存', '本月购进数量', '本月销售数量', '本月库存金额']) wf.flush() rf.close() wf.close()