在ubuntu下,新建.csv文件的方法是使用LibreOffice来创建一个数据表,然后我们把表格存储为.csv的格式:

“Save as”菜单把我们的表格存为一个CSV的文件格式:命名为csvData.csv:

name,num
zhangsan,123
lisi,456
wangwu,789

然后通过程序读写,如下图所示:

  

 # -- coding: utf-8 --

 import csv

 #读取csv文件方式1
csvFile = open("csvData.csv", "r")
reader = csv.reader(csvFile) # 返回的是迭代类型
data = []
for item in reader:
print(item)
data.append(item) print(data)
csvFile.close() #读取csv文件方式2
with open("csvData.csv", "r") as csvfile:
reader2 = csv.reader(csvfile)
for item2 in reader2:
print(item2)
csvFile.close()
~

输出结果:

['name', 'num']
['zhangsan', '']
['lisi', '']
['wangwu', '']
[['name', 'num'], ['zhangsan', ''], ['lisi', ''], ['wangwu', '']]
['name', 'num']
['zhangsan', '']
['lisi', '']
['wangwu', '']

参考文档:

https://www.cnblogs.com/liutongqing/p/6892099.html

04-14 02:09