Python csv 模块的简单使用

CSV文件 英文名:"comma seperated values"

以下为csv模块的代码块
原文档 addressbook.csv

name,age,telephone
stella,18,15000416462
jack,20,13725644371
lucy,17,13024267086

import csv

#由于我的csv文件带有BOM标记,转码后出现了'\ufeff',因而使用'utf-8-sig'的方式进行编码,正常情况下不需要另外声明,'utf-8'就好
with open('addressbook.csv','r',encoding='utf-8-sig') as csv_file:
    csv_reader = csv.DictReader(csv_file)

    with open('new_addressbook.csv','w')as new_file:
        #要写的列名
        fieldnames = ['name','age','telephone']

        csv_writer = csv.DictWriter(new_file,fieldnames=fieldnames,delimiter='\t') 
        #delimiter参数控制分割符

        #不加这一步的话,第一行列名将不会写入
        csv_writer.writeheader()

        for line in csv_reader:
            csv_writer.writerow(line)

读取addressbook.csv后,创建以空格分割的新的csv文件 new_addressbook.csv

stella  18  15000416462
jack    20  13725644371
lucy    17  13024267086

只读取addressbook.csv 的 name,telephone 字段

name    telephone
stella  15000416462
jack    13725644371
lucy    13024267086

import csv

#由于我的csv文件带有BOM标记,转码后出现了'\ufeff',因而使用'utf-8-sig'的方式进行编码,正常情况下不需要另外声明,'utf-8'就好
with open('addressbook.csv','r',encoding='utf-8-sig') as csv_file:
    csv_reader = csv.DictReader(csv_file)

    with open('new_addressbook.csv','w')as new_file:
        #控制要写的列名
        fieldnames = ['name','telephone']

        csv_writer = csv.DictWriter(new_file,fieldnames=fieldnames,delimiter='\t')

        csv_writer.writeheader()

        for line in csv_reader:
            #写入的时候,删除age这一dict
            del line['age']
            csv_writer.writerow(line)

你可能感兴趣的:(Python csv 模块的简单使用)