[Python Study Notes]csv文件操作

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
>>文件: csv文件操作.py
>>作者: liu yang
>>邮箱: liuyang0001@outlook.com
>>博客: www.cnblogs.com/liu66blog

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

# !/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os
import csv

data_list = \
    [
        ['name', 'age'],
        ['施名阳', 24],
        ['宋长武', 23],
        ['马云伟', 23],
    ]

# 写csv文件,加入newline='',防止每次都写入新行
with open('待写入csv文件.csv', 'w+', newline='', encoding='utf-8') as fp:
    csv_fp_write = csv.writer(fp)
    # 按行写入
    # for row in data_list:
    #     csv_fp_write.writerow(row)

    # 一次写入多行
    csv_fp_write.writerows(data_list)

# 使用csv.reader读文件
with open('待写入csv文件.csv', 'r', newline='', encoding='utf-8') as fp:
    csv_fp_read = csv.reader(fp)
    csv_list = list(csv_fp_read)
    print(csv_list)

######################################################################################
######################################################################################

data_dict = \
    [
        {'name': '施名阳', 'age': 24},
        {'name': '宋长武', 'age': 23},
        {'name': '马云伟', 'age': 23},
    ]

# 使用csv.DictWriter写文件
with open('待写入csv文件.csv', 'w+', newline='', encoding='utf-8') as fp:
    headers = ['name', 'age']
    csv_fp_write_dict = csv.DictWriter(fp, headers)
    csv_fp_write_dict.writeheader()
    # 按照行写入
    # for data in data_dict:
    #     csv_fp_write_dict.writerow(data)

    # 一次写入多行
    csv_fp_write_dict.writerows(data_dict)


# 使用csv.DictReader读取文件
with open('待写入csv文件.csv', 'r+', newline='', encoding='utf-8') as fp:
    # 按照字典一次性读取
    csv_fp_read_dict = csv.DictReader(fp)
    # 取得字典key值
    headers = csv_fp_read_dict.fieldnames
    print(headers)
    # 将可迭代列表化
    csv_fp_read_dict_list = list(csv_fp_read_dict)
    print(csv_fp_read_dict_list)
    # 定义一个空列表,用来存储字典列表
    csv_dict_list = []
    # 魂环读取到的列表,将其包装成字典,append到列表
    for csv_line in csv_fp_read_dict_list:
        csv_dict_list.append({headers[0]: csv_line[headers[0]], headers[1]: csv_line[headers[1]]})
    print(csv_dict_list)

 

image

posted @ 2018-02-25 18:03  刘六六  阅读(223)  评论(0编辑  收藏  举报