Python操作csv文件


什么是CSV

CSV全称”Comma Separated Values“,是一种格式化的文件,由行和列组成,分隔符可以根据需要来变化。

读取csv文件

我们使用python自带的csv模块来进行以下操作

我们新建一个csv文件,文件名为student.csv, 内容如下

Name,Age,Sex
Mary,18,Female
Tony,19,Male
Jack,20,Male

使用reader函数

import csv

with open("students.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

结果如下:

['Name', 'Age', 'Sex']
['Mary', '18', 'Female']
['Tony', '19', 'Male']
['Jack', '20', 'Male']

使用DictReader

import csv

with open("students.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)

结果如下

OrderedDict([('Name', 'Mary'), ('Age', '18'), ('Sex', 'Female')])
OrderedDict([('Name', 'Tony'), ('Age', '19'), ('Sex', 'Male')])
OrderedDict([('Name', 'Jack'), ('Age', '20'), ('Sex', 'Male')])

输出的结果为OrderedDict,可以将其转为dict类型

import csv

with open("students.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(dict(row))

结果如下

{'Name': 'Mary', 'Age': '18', 'Sex': 'Female'}
{'Name': 'Tony', 'Age': '19', 'Sex': 'Male'}
{'Name': 'Jack', 'Age': '20', 'Sex': 'Male'}

也可以像reader函数一样获取列表

import csv

with open("students.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader.reader:
        print(row)

结果如下

['Name', 'Age', 'Sex']
['Mary', '18', 'Female']
['Tony', '19', 'Male']
['Jack', '20', 'Male']

写入csv文件

使用writer函数

import csv

data = [
    ('Name', 'Age', 'Sex'),
    ('Jane', '16', 'Female'),
    ('Tom', '14', 'Male'),
    ('Leon', '15', 'Male'),
]
with open('student2.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(data)

写入的文件student2.csv内容如下

Name,Age,Sex
Jane,16,Female
Tom,14,Male
Leon,15,Male

使用DictWriter

import csv

data = [
    {'Name': 'Mark', 'Age': 17, 'Sex': 'Male'},
    {'Name': 'Lisa', 'Age': 16, 'Sex': 'Female'},
    {'Name': 'Jacky', 'Age': 20, 'Sex': 'Male'},
]
with open('student3.csv', 'w', newline='') as f:
    fieldnames = ['Name', 'Age', 'Sex']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(data)

写入的文件student3.csv内容如下

Name,Age,Sex
Mark,17,Male
Lisa,16,Female
Jacky,20,Male