Bootstrap

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. 进入到某一个单元格

import csv

with open(r'C:\Users\Anthony\Desktop\example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        # print(row)
        print(row[0])
        print(row[0],row[1])

4. 如何单独每列输出打印

import csv

with open(r'C:\Users\Anthony\Desktop\example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    citys = []
    password = []
    days = []
    for row in readCSV:
        city = row[0]
        paword = row[1]
        day = row[2]

        citys.append(city)
        password.append(paword)
        days.append(day)

    print(citys)
    print(password)    
    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']
>>> 


;