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