假设一个csv文件的内容如下:

姓名  年龄  成绩
张三  16  89
李四  15  76
王五  14  61

我们使用Python自带的csv库读取csv文件并在csv文件中写入新的内容。

1 Python读取csv文件

1.1 常规方法

读取上述csv文件的代码如下

# -*- coding: utf-8 -*-

import csv

def read_csv(csv_path):
    with open(csv_path, mode='r') as csv_file:
        csv_reader = csv.reader(csv_file)
        next(csv_reader) # 读取首行,跳过表头
        for line in csv_reader:
            if line[0] == '':
                continue

            name = line[0]
            age = line[1]
            score = line[2]

            print(f'{name} {age} {score}')

if __name__ == '__main__':
    read_csv('example.csv')

1.2 csv.DictReader方式

csv.DictReader读取csv文件,并将内容映射为字典形式,我们可以将每列的标题作为字典的键值读取每一行各列的值,并且此种方式不用使用next方式跳过第一行。

# -*- coding: utf-8 -*-

import csv

def read_csv(csv_path):
    with open(csv_path, mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)

        for line in csv_reader:

            name = line['姓名']
            age = line['年龄']
            score = line['成绩']

            print(f'{name} {age} {score}')

if __name__ == '__main__':
    read_csv('example.csv')

2 csv文件写入内容

2.1 常规方法

2.1.1 在现有文件上追加内容

# -*- coding: utf-8 -*-

import csv

def append_write_csv(csv_path):
    with open(csv_path, mode='a', newline='') as csv_file:
        csv_writer = csv.writer(csv_file)

        new_line = ['赵六','15','93']

        csv_writer.writerow(new_line)


if __name__ == '__main__':
    append_write_csv('example.csv')

2.1.2 覆盖已有csv内容,写入新的内容

# -*- coding: utf-8 -*-

import csv

def write_new_csv(csv_path):
    with open(csv_path, mode='w', newline='') as csv_file:
        csv_writer = csv.writer(csv_file)

        header = ['姓名','年龄','成绩']
        csv_writer.writerow(header)


        new_line = ['赵六','15','93']

        csv_writer.writerow(new_line)


if __name__ == '__main__':
    write_new_csv('example.csv')

2.2 csv.DictWriter

import csv

def write_new_csv(csv_path):
    with open(csv_path, mode='w', newline='') as csv_file:
        header = ['姓名', '年龄', '成绩']
        csv_writer = csv.DictWriter(csv_file,header)
        csv_writer.writeheader()

        csv_writer.writerow({"姓名": "赵六", "年龄": "15", "成绩": "93"})


if __name__ == '__main__':
    write_new_csv('example.csv')