csv文件——读和遍历csv文件

转载:https://automatetheboringstuff.com/2e/chapter16/

import csv

exampleFile = open('C:\\Users\\del\\Desktop\\123.csv')
exampleReader = csv.reader(exampleFile)

print(type(exampleReader))  #<class '_csv.reader'>

exampleData = list(exampleReader)          #转换为list列表,这样才方便访问

print(exampleData)
print('--------------------------------------1')
print(exampleData[0])
print(exampleData[1])
print(exampleData[2])
print(exampleData[3])

print('--------------------------------------2')

print(exampleData[0][0])
print(exampleData[0][1])
print(exampleData[0][2])

print('--------------------------------------3')

for row in exampleData:
    print(row)

执行结果:

C:\Python38\pythonw.exe C:/Users/del/PycharmProjects/untitled1/cs/api.py
<class '_csv.reader'>
[['4/4/2015 13:34', '苹果', '11'], ['4/5/2015 3:41', '香蕉', '22'], ['4/6/2015 12:46', '橘子', '33'], ['4/8/2015 8:59', '栗子', '44']]
--------------------------------------1
['4/4/2015 13:34', '苹果', '11']
['4/5/2015 3:41', '香蕉', '22']
['4/6/2015 12:46', '橘子', '33']
['4/8/2015 8:59', '栗子', '44']
--------------------------------------2
4/4/2015 13:34
苹果
11
--------------------------------------3
['4/4/2015 13:34', '苹果', '11']
['4/5/2015 3:41', '香蕉', '22']
['4/6/2015 12:46', '橘子', '33']
['4/8/2015 8:59', '栗子', '44']

Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/xiaobaibailongma/p/12387814.html