python基础—csv模块使用

时间:2022-07-22
本文章向大家介绍python基础—csv模块使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

csv文件使用逗号分割,是一种纯文本格式,不能指定字体颜色等样式,也不能指定单元格的宽高,不能合并单元格,没有多个工作表等功能,可以使用Excel打开。使用csv模块可以把一些数据做成表格等处理,非常方便。

CSV常用方法

csv.reader(f)   读取csv文件,f为打开csv文件的文件对象,返回的本质是一个迭代器,具有__next__(),__iter__()方法
csv.writer(f)   写入csv文件
csv.DictReader(f)    类字典方式读取csv文件
csv.DictWriter(f)    类字典方式写入csv文件

指定分隔符

csv.writer(f,delimiter='t')   指定分隔符为一个制表符,默认为逗号
csv.writer(f,delimiter=' ')    指定分隔符为空格

写入一行

file = csv.writer(f)
file.writerow([1,'tom'])

写入多行

data = [
    [1,'tom'],
    [2,'jerry'],
    [3,'harry']
]

with open('test.csv','w+') as f:
    file = csv.writer(f)
    for row in data:
        file.writerows(row)

示例一

from pathlib import Path
import csv

class CSV():
    def __init__(self,file,content):
        self.file = file
        self.content = content

    def CheckFile(self):    #检查文件是否存在,不存在则创建
        if not Path(self.file).parent.exists():
            Path(self.file).parent.mkdir(parents=True)
        else:
            if not Path(self.file).exists():
                Path(self.file).touch(exist_ok=True)

    def CSVRead(self):
        with open(str(self.file)) as f:
            reader = csv.reader(f)
            print(next(reader))

    def CSVWrite(self):
        with open(str(self.file),'a+') as f:
            w = csv.writer(f)
            for rows in self.content:
                w.writerow(rows)


if __name__ == '__main__':
    row = [[4,'tom',22,'tom'],
           [1,'james',34,'wade']
           ]
    fei = CSV('/Users/fei/tmp/ops/ccc.csv',row)
    fei.CSVWrite()
    with open('/Users/fei/tmp/ops/ccc.csv','r+') as f:
        read = csv.reader(f)    #读取csv文件,返回的是一个可迭代类型
        for file in read:
            print(read.line_num,file)

示例二

from pathlib import Path
import csv

class CSV():
    def __init__(self,file,header,content):
        self.file = file
        self.content = content
        self.header = header

    def CheckFile(self):
        if not Path(self.file).parent.exists():
            Path(self.file).parent.mkdir(parents=True)
        else:
            if not Path(self.file).exists():
                Path(self.file).touch(exist_ok=True)

    def CSVRead(self):
        with open(str(self.file)) as f:
            reader = csv.DictReader(f)
            for row in reader:
                print(row)

    def CSVWrite(self):
        with open(str(self.file),'a+',newline='') as f:
            w = csv.DictWriter(f,self.header)   #添加表头
            w.writeheader()      #调用添加表头的方法
            for row in self.content:
                w.writerow(row)

if __name__ == '__main__':

    headers = ['name','age']
    datas = [
        {'name': 'tom','age': 23},
        {'name': 'jerry','age': 24},
        {'name': 'james','age': 22}
    ]

    filecsv = CSV('/Users/fei/tmp/ops/ddd.csv',headers,datas)
    filecsv.CSVWrite()
    filecsv.CSVRead()