在ubuntu下,新建.csv文件的方法是使用LibreOffice来创建一个数据表,然后我们把表格存储为.csv的格式:
“Save as”菜单把我们的表格存为一个CSV的文件格式:命名为csvData.csv:
name,num zhangsan,123 lisi,456 wangwu,789
然后通过程序读写,如下图所示:
1 # -- coding: utf-8 -- 2 3 import csv 4 5 #读取csv文件方式1 6 csvFile = open("csvData.csv", "r") 7 reader = csv.reader(csvFile) # 返回的是迭代类型 8 data = [] 9 for item in reader: 10 print(item) 11 data.append(item) 12 13 print(data) 14 csvFile.close() 15 16 17 #读取csv文件方式2 18 with open("csvData.csv", "r") as csvfile: 19 reader2 = csv.reader(csvfile) 20 for item2 in reader2: 21 print(item2) 22 csvFile.close() 23 ~
输出结果:
['name', 'num'] ['zhangsan', '123'] ['lisi', '456'] ['wangwu', '789'] [['name', 'num'], ['zhangsan', '123'], ['lisi', '456'], ['wangwu', '789']] ['name', 'num'] ['zhangsan', '123'] ['lisi', '456'] ['wangwu', '789']