在 Python 中处理 CSV 文件通常使用 csv
模块。以下是一些常见的操作及示例代码:
读取 CSV 文件
import csv
def read_csv(file_path):
with open(file_path, mode='r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# 示例用法
file_path = 'example.csv'
read_csv(file_path)
写入 CSV 文件
import csv
def write_csv(file_path, data):
with open(file_path, mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerows(data)
# 示例用法
file_path = 'output.csv'
data = [
['Name', 'Age', 'City'],
['Alice', '30', 'New York'],
['Bob', '25', 'Los Angeles'],
['Charlie', '35', 'Chicago']
]
write_csv(file_path, data)
使用字典读取 CSV 文件
import csv
def read_csv_as_dict(file_path):
with open(file_path, mode='r', newline='', encoding='utf-8') as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
# 示例用法
file_path = 'example.csv'
read_csv_as_dict(file_path)
使用字典写入 CSV 文件
import csv
def write_csv_from_dict(file_path, fieldnames, data):
with open(file_path, mode='w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
# 示例用法
file_path = 'output.csv'
fieldnames = ['Name', 'Age', 'City']
data = [
{'Name': 'Alice', 'Age': '30', 'City': 'New York'},
{'Name': 'Bob', 'Age': '25', 'City': 'Los Angeles'},
{'Name': 'Charlie', 'Age': '35', 'City': 'Chicago'}
]
write_csv_from_dict(file_path, fieldnames, data)
读取大文件时的优化
对于大文件,可以考虑逐行处理,以减少内存使用:
import csv
def read_large_csv(file_path):
with open(file_path, mode='r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
# 处理每一行
print(row)
# 可以添加更多的处理逻辑
# 示例用法
file_path = 'large_example.csv'
read_large_csv(file_path)
处理包含空格或特殊字符的 CSV 文件
有时候 CSV 文件的字段值可能包含空格或特殊字符,这时候可以指定 csv
模块的参数,如 delimiter
和 quotechar
:
import csv
def read_special_csv(file_path):
with open(file_path, mode='r', newline='', encoding='utf-8') as file:
reader = csv.reader(file, delimiter=';', quotechar='"')
for row in reader:
print(row)
# 示例用法
file_path = 'special_example.csv'
read_special_csv(file_path)
这些示例涵盖了大多数常见的 CSV 文件处理需求,根据具体的应用场景,可以灵活运用这些方法和参数。