Python—csv

作者: 八戒无戒 | 来源:发表于2019-08-18 01:53 被阅读0次

Sometimes,we need save the data locally in order to convenient to view。As this time, wo can use Python's CSV package.

csv

CSV (Comma Separated Values),即逗号分隔值,python提供内置模块csv以操作csv文件。

1、写入csv文件

writer方法写入:

参数:writer(fileobj, dialect='excel', *args, **kwargs)

  • fileobj:为一个文件对象
  • dialect:编码风格,默认为excel的风格默认为excel的风格,也就是用逗号(,)分隔
  • delimiter: 可以指定分隔符
import csv
with open('test.csv','w+',encoding='utf8',newline='') as f:     #此处不加newline参数会出现空行
    c=csv.writer(f, delimiter=",")
    c.writerow(['id', 'name', 'age'])                                                    #写入一行
    c.writerows([('001','骷髅骑士',500), ('002','绯红女巫',20), ('003','美国队长',200)])  #写入多行

创建的csv文件:


image.png

DictWriter对象写入:

参数:DictWriter(f, fieldnames, [restval="", extrasaction="raise", dialect="excel", *args, **kwds])

  • f:文件对象
  • fieldnames:csv头部信息,也就是后面需要传入字典的键,将会根据该值来识别后面传入字典的序列进而写入csv文件
  • restval:如果字典缺少字段名中的键,则可选的restval参数指定要写入的值
  • extrasaction:如果传递的字典键字段名中找不到,则可选的extrasaction参数指示要采取的操作,可选'raise'和'ignore',后者字典中的额外值将被忽略
with open('test1.csv','w',newline="") as f:            #此处不加newline参数会出现空行
    w=csv.DictWriter(f,fieldnames=['id','name','age'],restval="aa",extrasaction='ignore')
    w.writeheader()                                    # 写入头部信息
    w.writerow({'id':'3','name':'灭霸','age':18})
    w.writerow({'id': '4', 'age': 18})
    w.writerows([{'id': '1', 'name': '卡罗拉', 'age': 18}, {'number': '2', 'name': '锤石', 'age': 23}])

image.png

可以看到两条异常数据,但程序并没有报错,因为设置了extrasaction为ignore,同时缺少的字段以’aa‘填充

2、读取csv文件

现有test.csv文件。


image.png

reader方法读取:

reader(iterable, [dialect='excel', *args, **kwargs])
参数:

  • iterable: 可迭代对象,此处传入一个文件对象
  • dialect:编码风格,默认为excel的风格默认为excel的风格,也就是用逗号(,)分隔
with open('test.csv', 'r') as f:
    r = csv.reader(f)
    for i in r:
        print(i)

>>>>>
['id', 'name', 'age']
['001', '骷髅骑士', '500']
['002', '绯红女巫', '20']
['003', '美国队长', '200']

DictReader对象读取:

DictReader(f, [fieldnames=None, restkey=None, restval=None,
dialect="excel", *args, **kwds])

  • f :文件对象
  • fieldnames :指定读取的字段,如果省略fieldnames,则文件f的第一行中的值将用作字段名
  • restkey :如果读取的字段少于一行包含的字段,则将剩余数据放入一个列表中,并使用restkey指定的字段名(默认为None)进行读取。
  • restval :如果读取的字段多于一行包含的字段,则将多余字段的值指定为restval的值(默认为None进行读取。
# 读取字段小于一行包含的字段
with open('test.csv', 'r') as f:
    r = csv.DictReader(f,['id','name'],restkey="hello")
    for i in r:
        print(i)
>>>
OrderedDict([('id', 'id'), ('name', 'name'), ('hello', ['age'])])
OrderedDict([('id', '1'), ('name', '骷髅骑士'), ('hello', ['500'])])
OrderedDict([('id', '2'), ('name', '绯红女巫'), ('hello', ['20'])])
OrderedDict([('id', '3'), ('name', '美国队长'), ('hello', ['200'])])

# 读取字段大于一行包含的字段
with open('test.csv', 'r') as f:
    r = csv.DictReader(f,['id','name','age','a'],restval="hello")
    for i in r:
        print(i)
>>>
OrderedDict([('id', 'id'), ('name', 'name'), ('age', 'age'), ('a', 'hello')])
OrderedDict([('id', '1'), ('name', '骷髅骑士'), ('age', '500'), ('a', 'hello')])
OrderedDict([('id', '2'), ('name', '绯红女巫'), ('age', '20'), ('a', 'hello')])
OrderedDict([('id', '3'), ('name', '美国队长'), ('age', '200'), ('a', 'hello')])

如果panda使用熟练的话,可以直接使用panda.read_csv()读取:

import pandas
result=pandas.read_csv('test.csv',encoding='gbk')
print(result)

>>>
   id  name  age
0   1  骷髅骑士  500
1   2  绯红女巫   20
2   3  美国队长  200

相关文章

网友评论

    本文标题:Python—csv

    本文链接:https://www.haomeiwen.com/subject/fujlsctx.html