Python 语言 CSV 文件读写 csv 模块基础

Python阿木 发布于 18 小时前 3 次阅读


阿木博主一句话概括:深入浅出Python CSV文件读写:csv模块应用详解

阿木博主为你简单介绍:
CSV(Comma-Separated Values,逗号分隔值)文件是一种常见的文本文件格式,用于存储表格数据。Python的csv模块提供了读取和写入CSV文件的功能,是处理CSV数据的一个强大工具。本文将围绕Python语言中的csv模块,详细介绍CSV文件的读写操作,包括基本概念、常用方法以及实际应用案例。

一、CSV文件基本概念

CSV文件是一种以逗号分隔的纯文本文件,通常用于数据交换和存储。每行代表一个数据记录,每个字段由逗号分隔。CSV文件不包含任何格式信息,如字体、颜色等。

二、Python csv模块简介

Python的csv模块提供了读取和写入CSV文件的功能,包括以下常用方法:

1. `csv.reader()`:用于读取CSV文件。
2. `csv.writer()`:用于写入CSV文件。
3. `csv.DictReader()`:以字典形式读取CSV文件。
4. `csv.DictWriter()`:以字典形式写入CSV文件。

三、CSV文件读取

1. 使用`csv.reader()`读取CSV文件

python
import csv

with open('example.csv', 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)

2. 使用`csv.DictReader()`读取CSV文件

python
import csv

with open('example.csv', 'r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['name'], row['age'])

四、CSV文件写入

1. 使用`csv.writer()`写入CSV文件

python
import csv

with open('output.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['name', 'age'])
writer.writerow(['Alice', 25])
writer.writerow(['Bob', 30])

2. 使用`csv.DictWriter()`写入CSV文件

python
import csv

with open('output.csv', 'w', encoding='utf-8', newline='') as csvfile:
fieldnames = ['name', 'age']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'name': 'Alice', 'age': 25})
writer.writerow({'name': 'Bob', 'age': 30})

五、实际应用案例

1. 数据导入导出

使用csv模块可以将数据从CSV文件导入到Python程序中,也可以将程序中的数据导出到CSV文件。

python
导入数据
with open('data.csv', 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
data = list(reader)

导出数据
with open('output.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)

2. 数据清洗

使用csv模块可以方便地对CSV文件中的数据进行清洗,如去除空行、去除重复行等。

python
import csv

with open('data.csv', 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
data = [row for row in reader if row] 去除空行

with open('cleaned_data.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)

六、总结

Python的csv模块为处理CSV文件提供了便捷的方法。相信读者已经掌握了CSV文件的基本概念、读取和写入方法,以及实际应用案例。在实际开发中,熟练运用csv模块可以大大提高数据处理效率。

注意:在实际应用中,可能需要根据具体需求对csv模块进行扩展,如自定义分隔符、处理特殊字符等。对于大型CSV文件,建议使用更高效的文件处理方法,如使用pandas库等。