python csv 简单操作

2021-05-04 16:29

阅读:630

标签: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


评论


亲,登录后才可以留言!