本文来介绍用Python读取csv文件。什么是csv(Comma-Separated Values),也叫逗号分割值,如果你安装了excel,默认会用excel打开csv文件。
- 我们先制作一个csv文件,example.csv
-
看看如何用Python来读取这个文件
1
2
3
4
5
6
7
8 1import csv
2
3with open(r'C:\Users\Anthony\Desktop\example.csv') as csvfile:
4 readCSV = csv.reader(csvfile, delimiter=',')
5 for row in readCSV:
6 print(row)
7
8
运行输出效果
['city', 'password', 'day']
['Beijing', 'DJOYnieT8234jlsK', '1']
['Shanghai', 'DJOYnieT8234jlsK', '2']
['Guangzhou', 'DJOYnieT8234jlsK', '3']
['Shenzhen', 'DJOYnieT8234jlsK', '1']
- 进入到某一个单元格
1
2
3
4
5
6
7
8
9 11 import csv
22
33 with open(r'C:\Users\Anthony\Desktop\example.csv') as csvfile:
44 readCSV = csv.reader(csvfile, delimiter=',')
55 for row in readCSV:
66 # print(row)
77 print(row[0])
88 print(row[0],row[1])
9
- 如何单独每列输出打印
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 11 import csv
2 2
3 3 with open(r'C:\Users\Anthony\Desktop\example.csv') as csvfile:
4 4 readCSV = csv.reader(csvfile, delimiter=',')
5 5 citys = []
6 6 password = []
7 7 days = []
8 8 for row in readCSV:
9 9 city = row[0]
1010 paword = row[1]
1111 day = row[2]
1212
1313 citys.append(city)
1414 password.append(paword)
1515 days.append(day)
1616
1717 print(citys)
1818 print(password)
1919 print(days)
20
上面这个r表示不需要转义,原义输出,因为上面有\,反斜杠默认是转义,所以需要添加r
输出效果
================= RESTART: C:\Users\Anthony\Desktop\demo.py =================
['city', 'Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen']
['password', 'DJOYnieT8234jlsK', 'DJOYnieT8234jlsK', 'DJOYnieT8234jlsK', 'DJOYnieT8234jlsK']
['day', '1', '2', '3', '1']