码迷,mamicode.com
首页 > 编程语言 > 详细

python csv 简单操作

时间:2020-06-26 14:24:39      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:write   names   lin   简单操作   end   pen   nat   port   处理   

# -*- 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文件

python csv 简单操作

标签:write   names   lin   简单操作   end   pen   nat   port   处理   

原文地址:https://www.cnblogs.com/xgege/p/13194526.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!