python 操作csv

Posted 西北逍遥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 操作csv相关的知识,希望对你有一定的参考价值。

python 操作csv

 

写csv

import csv

with open(\'path/to/file.csv\', \'w\', newline=\'\') as csvfile:
    writer = csv.writer(csvfile, delimiter=\',\', quotechar=\'"\', quoting=csv.QUOTE_MINIMAL)
    writer.writerow([\'Name\', \'Age\', \'Gender\'])
    writer.writerow([\'Alice\', \'25\', \'Female\'])
    writer.writerow([\'Bob\', \'30\', \'Male\'])

  

读csv

import csv

with open(\'path/to/file.csv\', newline=\'\') as csvfile:
    reader = csv.reader(csvfile, delimiter=\',\', quotechar=\'"\')
    for row in reader:
        print(\', \'.join(row))

  

 

 

 

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

Python中csv文件操作

1.csv写入

技术分享图片
"""csv两种写入操作"""
import csv


def write_csv_demo():
    headers = ["username", "age", "height"]
    values = {
        ("张三", 18, 180),
        ("李四", 19, 190),
        ("王五", 20, 160)
    }

    # 写入编码utf-8防止乱码,newline默认
换行,防止换行让它等于空字符串
    with open("classroom.csv", "w", encoding="utf-8", newline="") as fp:
        # 创建一个文件句柄对象
        writer = csv.writer(fp)
        # 写入一行writerow
        writer.writerow(headers)
        # 写入多行writerows
        writer.writerows(values)


def write_csv_site():
    headers = ["username", "age", "height"]
    values = [
        {"username": "张三", "age": 18, "height": 180},
        {"username": "李四", "age": 19, "height": 190},
        {"username": "王五", "age": 20, "height": 160},
    ]
    with open("classroom1.csv", "w", encoding="utf-8", newline="") as fp:
        # DictWriter需要传入一个文件句柄和字典的key列表
        writer = csv.DictWriter(fp, headers)
        # 正式写入需要调用writeheader方法
        writer.writeheader()
        writer.writerows(values)


if __name__ == __main__:
    write_csv_site()
View Code

2.csv读取

技术分享图片
"""读取csv文件的两种方式"""
import csv


def read_csv_demo():
    # 优势:操作简单。劣势:数据排序混乱时取值可能报错
    with open("classroom.csv", "r", encoding="utf-8") as fp:
        # reader是一个迭代器
        reader = csv.reader(fp)
        # 执行一次next,指针跳过一位,可以不获取标题
        next(reader)
        for x in reader:
            print(x)  # 可用列表下标x[1]获取具体对象


def read_csv_site():
    # 优势:即便数据混乱也可以通过key取值。劣势:稍复杂一点
    with open("classroom1.csv", "r", encoding="utf-8") as fp:
        # 使用DictReader创建的reader对象不会包含标签这一行的数据
        reader = csv.DictReader(fp)
        # 遍历reader迭代器返回的是一个有序字典
        for x in reader:
            value = {"name": x["username"], "age": x["age"]}
            print(value)


if __name__ == __main__:
    read_csv_site()
View Code

 

以上是关于python 操作csv的主要内容,如果未能解决你的问题,请参考以下文章

python之csv操作

Python中csv文件操作

python 操作csv

Python操作csv文件

python读写操作csv及excle文件

21天学习python编程_csv文件操作