- Python教程
- Python 简介
- Python3 下载安装
- python基础语法
- Python基本数据类型
- Python数据类型转换
- Python解释器
- Python 注释
- Python运算符
- Python数字(Number)
- Python字符串
- Python列表
- Python元组
- Python3 字典
- Python集合
- Python条件控制
- Python循环语句
- Python编程第一步
- Python 推导式
- Python3 迭代器与生成器
- Python函数
- Python lambda(匿名函数)
- Python 装饰器
- Python数据结构
- Python3 模块
- Python __name__ 与 __main__
- Python输入和输出
- Python3 File(文件) 方法
- Python3 OS 文件/目录方法
- Python3 错误和异常
- Python3 面向对象
- Python3 命名空间和作用域
- Python3 标准库概览
- -----高级教程----------
- Python3 正则表达式
- Python CGI编程
- Python MySQL - mysql-connector 驱动
- Python3 MySQL 数据库连接 - PyMySQL 驱动
- Python3 网络编程
- Python3 SMTP发送邮件
- Python3 多线程
- Python3 XML 解析
- Python3 JSON 数据解析
- Python3 日期和时间
- Python MongoDB
- **Python Mongodb 插入文档
- **Python Mongodb 查询文档
- **Python Mongodb 修改文档
- **Python Mongodb 排序
- **Python Mongodb 删除数据
- Python urllib
- Python uWSGI 安装配置
- Python3 pip
- Anaconda 教程
- Python3 operator 模块
- Python math 模块
- Python requests 模块
- Python random 模块
- Python AI 绘画
- Python statistics 模块
- Python hashlib 模块
- Python 量化
- Python pyecharts 模块
- Python selenium 库
- Python 爬虫 - BeautifulSoup
- Python Scrapy 库
- Python Markdown 生成 HTML
- Python sys 模块
- Python Pickle 模块
- Python subprocess 模块
- Python queue 模块
- Python StringIO 模块
- Python logging 模块
- Python datetime 模块
- Python re 模块
- Python csv 模块
- Python threading 模块
- Python asyncio 模块
- Python PyQt
- **Python PyQt 常用组件
- **Python PyQt 布局管理
- **Python PyQt 信号与槽机制
CSV(Comma-Separated Values)文件是一种常见的文件格式,用于存储表格数据。
CSV 文件由纯文本组成,每一行代表表格中的一行数据,而每一列则通过逗号(或其他分隔符)分隔。
CSV 文件通常用于数据交换,因为它简单且易于处理。
Python 提供了一个内置的 csv
模块,用于读取和写入 CSV 文件。这个模块简化了处理 CSV 文件的过程,使得开发者可以轻松地操作表格数据。
1. 读取 CSV 文件
要读取 CSV 文件,可以使用 csv.reader
对象。以下是一个简单的示例:
实例
import csv # 打开 CSV 文件 with open('data.csv', mode='r', encoding='utf-8') as file: # 创建 csv.reader 对象 csv_reader = csv.reader(file) # 逐行读取数据 for row in csv_reader: print(row)
代码解释:
open('data.csv', mode='r', encoding='utf-8')
:以只读模式打开名为data.csv
的文件,并指定编码为 UTF-8。csv.reader(file)
:创建一个csv.reader
对象,用于读取文件内容。for row in csv_reader
:逐行读取文件内容,每一行数据会被解析为一个列表。
2. 写入 CSV 文件
要写入 CSV 文件,可以使用 csv.writer
对象。以下是一个示例:
实例
import csv # 要写入的数据 data = [ ['Name', 'Age', 'City'], ['Alice', '30', 'New York'], ['Bob', '25', 'Los Angeles'] ] # 打开 CSV 文件 with open('output.csv', mode='w', encoding='utf-8', newline='') as file: # 创建 csv.writer 对象 csv_writer = csv.writer(file) # 写入数据 for row in data: csv_writer.writerow(row)
代码解释:
open('output.csv', mode='w', encoding='utf-8', newline='')
:以写入模式打开名为output.csv
的文件,并指定编码为 UTF-8。newline=''
用于避免在 Windows 系统中出现空行。csv.writer(file)
:创建一个csv.writer
对象,用于写入文件内容。csv_writer.writerow(row)
:将每一行数据写入文件。
3. 使用字典读取和写入 CSV 文件
csv
模块还提供了 DictReader
和 DictWriter
类,它们可以将 CSV 文件的每一行解析为字典,或者将字典写入 CSV 文件。
使用 DictReader
读取 CSV 文件:
实例
import csv with open('data.csv', mode='r', encoding='utf-8') as file: csv_dict_reader = csv.DictReader(file) for row in csv_dict_reader: print(row)
使用 DictWriter
写入 CSV 文件:
实例
import csv data = [ {'Name': 'Alice', 'Age': '30', 'City': 'New York'}, {'Name': 'Bob', 'Age': '25', 'City': 'Los Angeles'} ] with open('output.csv', mode='w', encoding='utf-8', newline='') as file: fieldnames = ['Name', 'Age', 'City'] csv_dict_writer = csv.DictWriter(file, fieldnames=fieldnames) # 写入表头 csv_dict_writer.writeheader() # 写入数据 for row in data: csv_dict_writer.writerow(row)
常用的属性和方法
csv 模块核心方法
方法 | 说明 | 示例 |
---|---|---|
csv.reader() | 从文件对象读取 CSV 数据 | reader = csv.reader(file) |
csv.writer() | 将数据写入 CSV 文件 | writer = csv.writer(file) |
csv.DictReader() | 将 CSV 行读取为字典(带表头) | dict_reader = csv.DictReader(file) |
csv.DictWriter() | 将字典写入 CSV 文件(需指定字段名) | dict_writer = csv.DictWriter(file, fieldnames) |
csv.register_dialect() | 注册自定义 CSV 格式(如分隔符) | csv.register_dialect('mydialect', delimiter='|') |
csv.unregister_dialect() | 删除已注册的方言 | csv.unregister_dialect('mydialect') |
csv.list_dialects() | 列出所有已注册的方言 | print(csv.list_dialects()) |
csv.reader 和 csv.writer 对象常用方法
方法 | 说明 | 适用对象 |
---|---|---|
__next__() | 迭代读取下一行(或使用 for 循环) | reader |
writerow(row) | 写入单行数据 | writer |
writerows(rows) | 写入多行数据(列表的列表) | writer |
csv.DictReader 和 csv.DictWriter 对象特性
特性/方法 | 说明 | 示例 |
---|---|---|
fieldnames | 字段名列表(DictReader 自动从首行获取) | dict_reader.fieldnames |
writeheader() | 写入表头行(DictWriter 专用) | dict_writer.writeheader() |
常用参数说明
参数 | 说明 | 示例值 | 适用方法 |
---|---|---|---|
delimiter | 字段分隔符 | ',' (默认), '\t' | reader/writer |
quotechar | 引用字符(包围特殊字段) | '"' (默认) | reader/writer |
quoting | 引用规则 | csv.QUOTE_ALL (全部引用) | reader/writer |
skipinitialspace | 忽略分隔符后的空格 | True /False | reader |
lineterminator | 行结束符 | '\r\n' (默认) | writer |
dialect | 预定义的方言名称 | 'excel' (默认) | 所有方法 |
实例
1. 读取 CSV 文件
实例
import csv with open('data.csv', 'r') as file: reader = csv.reader(file, delimiter=',') for row in reader: print(row) # 每行是一个列表
2. 写入 CSV 文件
实例
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]] with open('output.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(data) # 写入多行
3. 使用 DictReader 和 DictWriter(带表头)
实例
# 读取 with open('data.csv', 'r') as file: dict_reader = csv.DictReader(file) for row in dict_reader: print(row['Name'], row['Age']) # 通过字段名访问 # 写入 fieldnames = ['Name', 'Age'] with open('output.csv', 'w', newline='') as file: dict_writer = csv.DictWriter(file, fieldnames=fieldnames) dict_writer.writeheader() # 写入表头 dict_writer.writerow({'Name': 'Alice', 'Age': 25})
4. 自定义方言(如处理 TSV 文件)
实例
csv.register_dialect('tsv', delimiter='\t', quoting=csv.QUOTE_NONE) with open('data.tsv', 'r') as file: reader = csv.reader(file, dialect='tsv') for row in reader: print(row)