python csv 简单操作

txlCandy 2020-06-26

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

import csv

data1 = [[‘name‘, ‘age‘, ‘sex‘],
         [‘张三‘, ‘19‘, ‘男‘],
         [‘李四‘, ‘22‘, ‘男‘],
         [‘王五‘, ‘20‘, ‘男‘],
         [‘赵六‘, ‘18‘, ‘女‘]]

# writer
with open(‘csvFile1.csv‘, ‘w‘) as file:
    # 解决中间有空行,也可以在open函数中加newline=‘‘解决
    writer = csv.writer(file, lineterminator=‘\n‘)
    writer.writerows(data1)

# reader
with open(‘csvFile1.csv‘) as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# DicReader
data2 = []
with open(‘csvFile1.csv‘) as file:
    dic_reader = csv.DictReader(file)
    for row in dic_reader:
        print(row)
        data2.append(row)

# DicWriter
header_data = [‘name‘, ‘age‘, ‘sex‘]
with open(‘csvFile2.csv‘, ‘w‘, newline=‘‘) as file:
    dic_writer = csv.DictWriter(file, fieldnames=header_data)
    dic_writer.writeheader()
    for row in data2:
        dic_writer.writerow(row)

参考连接

Python CSV 教程|极客教程

用python玩转csv文件:csv模块

Python处理csv文件

相关推荐