
手动拼接字符串来生成csv行是一种常见的错误源,尤其当数据字段本身包含逗号或特殊字符时,极易导致格式错乱。本文将深入探讨手动csv写入的陷阱,并推荐使用python标准库中的csv模块,通过其自动引用和转义机制,确保数据以正确的csv格式写入,从而避免数据字段混淆的问题。
在处理包含复杂文本或多值字段(如多个标签或详细描述)的数据时,直接使用字符串拼接(例如 field1 + ',' + field2)来构建CSV行会遇到严重问题。CSV文件通过逗号分隔字段,并使用双引号来引用包含逗号、双引号或换行符的字段。如果一个字段本身含有逗号,而我们没有对其进行适当的引用,CSV解析器会将其误认为是多个字段。
考虑一个动漫数据写入CSV的场景,其中包含标题、流派(多个流派以逗号分隔)和剧情简介。如果流派字段是 "Adventure, Fantasy, Shounen, Supernatural",而剧情简介字段是 "It is the dark century..."。当我们手动拼接时:
# 假设 genres = "Adventure, Fantasy, Shounen, Supernatural" # 假设 synopsis = "It is the dark century..." # 手动拼接示例: # details = ..., genres + ',' + synopsis # 最终的字符串可能是: # "Adventure, Fantasy, Shounen, Supernatural,It is the dark century..."
如果CSV文件没有正确引用 genres 字段,解析器会将其中的逗号视为字段分隔符,导致 Fantasy、Shounen、Supernatural 甚至部分 synopsis 被错误地识别为独立的字段。
实际问题示例:
立即学习“Python免费学习笔记(深入)”;
预期格式(正确引用): "8","Bouken Ou Beet","2004-09-30","6.93","4426","5274","52","pg","Toei Animation","Adventure, Fantasy, Shounen, Supernatural", "It is the dark century and the people are suffering under the rule of the devil Vandel who is able to manipulate monsters."
实际输出(错误引用导致字段混淆): "8","Bouken Ou Beet","2004-09-30","6.93","4426","5274","52","pg","Toei Animation","Adventure"," Fantasy Shounen SupernaturalIt is the dark century and the people are suffering under the rule of the devil Vandel who is able to manipulate monsters."
可以看到,"Adventure" 被单独引用,而后面的 Fantasy Shounen Supernatural 与 synopsis 混在了一起,因为它们没有被正确地双引号包裹。
Python的 csv 模块提供了强大的功能来处理CSV文件,它能够自动处理字段的引用、转义和分隔,从而避免手动拼接带来的各种问题。csv 模块主要提供 csv.writer 和 csv.DictWriter 两种写入器。
在写入CSV之前,首先需要将数据解析并组织成结构化的形式,例如列表的列表(用于 csv.writer)或字典的列表(用于 csv.DictWriter)。
假设我们有一个 parse_data 函数,它从API响应中提取信息并返回一个包含所有字段的列表或字典:
import re
def parse_anime_data(data):
"""
解析原始动漫数据并返回一个结构化的列表。
"""
try:
# Genre parse
genres_list = data.get('genres', [])
genres = ', '.join(genre['name'] for genre in genres_list) if genres_list else ""
# Studio parse
studio_name = "unknown"
studio_parse = str(data.get('studios'))
match = re.search(r"'name':\s*'([^']*)'", studio_parse)
if match:
studio_name = match.group(1)
# Synopsis parse
synopsis_dirty = data.get('synopsis', '')
synopsis = re.sub(r"\(Source: [^\)]+\)", "", synopsis_dirty).strip()
synopsis = re.sub(r'\[Written by MAL Rewrite\]', '', synopsis).strip()
# 返回一个列表,每个元素都是一个字段
return [
str(data.get('id', '')),
data.get('title', '').encode('utf-8').decode('cp1252', 'replace'),
data.get('start_date', ''),
str(data.get('mean', '')),
str(data.get('rank', '')),
str(data.get('popularity', '')),
str(data.get('num_episodes', '')),
data.get('rating', ''),
studio_name,
genres, # 此时genres是一个包含逗号的字符串
synopsis # 此时synopsis是一个可能包含逗号或换行符的字符串
]
except Exception as e:
print(f"Error parsing data: {e}")
return None
# 示例原始数据(简化版)
sample_api_data = {
'id': 8,
'title': 'Bouken Ou Beet',
'start_date': '2004-09-30',
'mean': 6.93,
'rank': 4426,
'popularity': 5274,
'num_episodes': 52,
'rating': 'pg',
'studios': [{'id': 18, 'name': 'Toei Animation'}],
'genres': [{'id': 2, 'name': 'Adventure'}, {'id': 10, 'name': 'Fantasy'}, {'id': 27, 'name': 'Shounen'}, {'id': 37, 'name': 'Supernatural'}],
'synopsis': 'It is the dark century and the people are suffering under the rule of the devil Vandel who is able to manipulate monsters. (Source: MAL Rewrite)'
}
parsed_row = parse_anime_data(sample_api_data)
# parsed_row 现在是:
# ['8', 'Bouken Ou Beet', '2004-09-30', '6.93', '4426', '5274', '52', 'pg', 'Toei Animation', 'Adventure, Fantasy, Shounen, Supernatural', 'It is the dark century and the people are suffering under the rule of the devil Vandel who is able to manipulate monsters.']csv.writer 适用于写入列表形式的数据。它接受一个文件对象作为参数,并提供 writerow() 方法来写入单行数据,以及 writerows() 方法来写入多行数据。
import csv
def write_data_to_csv_writer(filename, data_rows, header=None):
"""
使用 csv.writer 将数据写入CSV文件。
:param filename: CSV文件名。
:param data_rows: 包含要写入的数据的列表的列表。
:param header: 可选的列表,作为CSV的标题行。
"""
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
csv_writer = csv.writer(csvfile)
if header:
csv_writer.writerow(header) # 写入标题行
for row in data_rows:
csv_writer.writerow(row) # 写入数据行
print(f"Data successfully written to {filename} using csv.writer.")
# 示例使用
header = ["id", "title", "start-date", "mean", "rank", "popularity", "num_episodes", "rating", "studio", "genres", "synopsis"]
all_anime_data = [parsed_row] # 假设这里有多个解析好的行
write_data_to_csv_writer("anime_data_writer.csv", all_anime_data, header)使用 csv.writer 写入后,genres 和 synopsis 字段即使包含逗号,也会被自动用双引号引用,确保CSV格式的正确性。
csv.DictWriter 更适合处理字典形式的数据,它允许你通过字典键来指定字段,提高了代码的可读性和维护性。
首先,我们需要调整 parse_anime_data 函数,使其返回一个字典:
def parse_anime_data_to_dict(data):
"""
解析原始动漫数据并返回一个结构化的字典。
"""
try:
genres_list = data.get('genres', [])
genres = ', '.join(genre['name'] for genre in genres_list) if genres_list else ""
studio_name = "unknown"
studio_parse = str(data.get('studios'))
match = re.search(r"'name':\s*'([^']*)'", studio_parse)
if match:
studio_name = match.group(1)
synopsis_dirty = data.get('synopsis', '')
synopsis = re.sub(r"\(Source: [^\)]+\)", "", synopsis_dirty).strip()
synopsis = re.sub(r'\[Written by MAL Rewrite\]', '', synopsis).strip()
return {
"id": str(data.get('id', '')),
"title": data.get('title', '').encode('utf-8').decode('cp1252', 'replace'),
"start-date": data.get('start_date', ''),
"mean": str(data.get('mean', '')),
"rank": str(data.get('rank', '')),
"popularity": str(data.get('popularity', '')),
"num_episodes": str(data.get('num_episodes', '')),
"rating": data.get('rating', ''),
"studio": studio_name,
"genres": genres,
"synopsis": synopsis
}
except Exception as e:
print(f"Error parsing data to dict: {e}")
return None
parsed_dict_row = parse_anime_data_to_dict(sample_api_data)
# parsed_dict_row 现在是:
# {'id': '8', 'title': 'Bouken Ou Beet', ..., 'genres': 'Adventure, Fantasy, Shounen, Supernatural', 'synopsis': 'It is the dark century and the people are suffering under the rule of the devil Vandel who is able to manipulate monsters.'}然后,使用 csv.DictWriter 写入:
def write_data_to_csv_dictwriter(filename, data_dicts, fieldnames):
"""
使用 csv.DictWriter 将数据写入CSV文件。
:param filename: CSV文件名。
:param data_dicts: 包含要写入的数据的字典列表。
:param fieldnames: 字典的键列表,用于定义CSV的列顺序和标题。
"""
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
csv_writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
csv_writer.writeheader() # 写入标题行(根据fieldnames)
csv_writer.writerows(data_dicts) # 写入数据行
print(f"Data successfully written to {filename} using csv.DictWriter.")
# 示例使用
fieldnames = ["id", "title", "start-date", "mean", "rank", "popularity", "num_episodes", "rating", "studio", "genres", "synopsis"]
all_anime_data_dicts = [parsed_dict_row] # 假设这里有多个解析好的字典行
write_data_to_csv_dictwriter("anime_data_dictwriter.csv", all_anime_data_dicts, fieldnames)手动拼接字符串来生成CSV文件是一种高风险的操作,尤其是在数据复杂性增加时。Python的 csv 模块提供了一个健壮、高效且易于使用的解决方案,能够自动处理CSV格式的各种细节,包括字段引用和特殊字符转义。通过采用 csv.writer 或 csv.DictWriter,开发者可以专注于数据的解析和组织,而无需担心CSV格式的底层实现,从而确保生成的文件符合标准且易于被其他工具正确解析。在任何需要写入CSV的Python项目中,强烈建议优先考虑使用 csv 模块。
以上就是Python CSV写入格式化问题:使用标准库csv模块避免常见陷阱的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号