PythonCSV写入带引号数据的解决方法
时间:2025-07-14 11:39:25 148浏览 收藏
偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《Python CSV写入引号问题解决方法》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

本文旨在解决在使用Python的csv.writer模块时,输出CSV文件内容被双引号包裹的问题。通过详细的代码示例和参数解释,展示如何正确设置csv.reader和csv.writer的参数,避免不必要的引号,并提供一个完整的解决方案,用于在指定CSV列中替换字符串。
问题背景
在使用Python的csv模块处理CSV文件时,有时会遇到csv.writer自动将数据用双引号包裹的情况,这通常是由于默认的quoting参数设置导致的。 如果不希望输出的CSV文件中包含这些额外的引号,就需要对csv.writer和csv.reader的参数进行适当的调整。
解决方案
核心在于正确配置csv.reader和csv.writer的参数,特别是delimiter、quotechar、escapechar和quoting。
关键参数解析
delimiter: 指定字段之间的分隔符。 默认为逗号 (,)。
quotechar: 指定包围含有特殊字符(例如 delimiter)的字段的字符。 默认为双引号 (")。
escapechar: 用于转义 quotechar 的字符。
quoting: 控制何时应用引号。 常用的选项包括:
- csv.QUOTE_ALL: 引用所有字段。
- csv.QUOTE_MINIMAL: 只引用包含 delimiter、quotechar 或 lineterminator 等特殊字符的字段。 这是默认选项。
- csv.QUOTE_NONNUMERIC: 引用所有非数字字段。
- csv.QUOTE_NONE: 不引用任何字段。 当使用此选项时,必须同时指定 escapechar,以便转义 delimiter。
代码示例
以下代码展示了如何使用csv.reader和csv.writer,并禁用引号,以及如何在指定列中替换字符串:
import csv, io
import os, shutil
result = {}
csv_file_path = 'myreport.csv'
columns_to_process = ['money1', 'money2']
string_to_be_replaced = "."
string_to_replace_with = ","
mydelimiter = ";"
# check file existence
if not os.path.isfile(csv_file_path):
raise IOError("csv_file_path is not valid or does not exists: {}".format(csv_file_path))
# check the delimiter existence
with open(csv_file_path, 'r') as csvfile:
first_line = csvfile.readline()
if mydelimiter not in first_line:
delimiter_warning_message = "No delimiter found in file first line."
result['warning_messages'].append(delimiter_warning_message)
# count the lines in the source file
NOL = sum(1 for _ in io.open(csv_file_path, "r"))
if NOL > 0:
# just get the columns names, then close the file
#-----------------------------------------------------
with open(csv_file_path, 'r') as csvfile:
columnslist = csv.DictReader(csvfile, delimiter=mydelimiter)
list_of_dictcolumns = []
# loop to iterate through the rows of csv
for row in columnslist:
# adding the first row
list_of_dictcolumns.append(row)
# breaking the loop after the
# first iteration itself
break
# transform the colum names into a list
first_dictcolumn = list_of_dictcolumns[0]
list_of_column_names = list(first_dictcolumn.keys())
number_of_columns = len(list_of_column_names)
# check columns existence
#------------------------
column_existence = [ (column_name in list_of_column_names ) for column_name in columns_to_process ]
if not all(column_existence):
raise ValueError("File {} does not contains all the columns given in input for processing:\nFile columns names: {}\nInput columns names: {}".format(csv_file_path, list_of_column_names, columns_to_process))
# determine the indexes of the columns to process
indexes_of_columns_to_process = [i for i, column_name in enumerate(list_of_column_names) if column_name in columns_to_process]
print("indexes_of_columns_to_process: ", indexes_of_columns_to_process)
# build the path of a to-be-generated duplicate file to be used as output
inputcsv_absname, inputcsv_extension = os.path.splitext(csv_file_path)
csv_output_file_path = inputcsv_absname + '__output' + inputcsv_extension
# define the processing function
def replace_string_in_columns(input_csv, output_csv, indexes_of_columns_to_process, string_to_be_replaced, string_to_replace_with):
number_of_replacements = 0
with open(input_csv, 'r', newline='') as infile, open(output_csv, 'w', newline='') as outfile:
reader = csv.reader(infile, quoting=csv.QUOTE_NONE, delimiter=mydelimiter, quotechar='',escapechar='\\')
writer = csv.writer(outfile, quoting=csv.QUOTE_NONE, delimiter=mydelimiter, quotechar='',escapechar='\\')
row_index=0
for row in reader:
for col_index in indexes_of_columns_to_process:
# break the processing when empty lines at the end of the file are reached
if len(row) == 0:
break
cell = row[col_index]
columns_before = row[:col_index]
columns_after = row[(col_index + 1):]
print("col_index: ", col_index)
print("row: ", row)
print("cell: ", cell)
if string_to_be_replaced in cell and row_index != 0:
# do the substitution in the cell
cell = cell.replace(string_to_be_replaced, string_to_replace_with)
number_of_replacements = number_of_replacements + 1
print("number_of_replacements: ", number_of_replacements)
# # sew the row up agian
row_replaced = columns_before + [ cell ] + columns_after
row = row_replaced
# write / copy the row in the new file
writer.writerow(row)
print("written row: ", row, "index: ", row_index)
row_index=row_index+1
return number_of_replacements
# launch the function
result['number_of_modified_cells'] = replace_string_in_columns(csv_file_path, csv_output_file_path, indexes_of_columns_to_process, string_to_be_replaced, string_to_replace_with)
# replace the old csv with the new one
shutil.copyfile(csv_output_file_path, csv_file_path)
os.remove(csv_output_file_path)
if result['number_of_modified_cells'] > 0:
result['changed'] = True
else:
result['changed'] = False
else:
result['changed'] = False
result['source_csv_number_of_raw_lines'] = NOL
result['source_csv_number_of_lines'] = NOL - 1
print("result:\n\n", result)代码解释:
- 导入必要的模块: 导入csv, io, os 和 shutil 模块。
- 定义参数: 定义CSV文件路径、需要处理的列名、要替换的字符串、替换后的字符串以及分隔符。
- 文件检查: 检查CSV文件是否存在,以及分隔符是否存在于第一行中。
- 读取列名: 使用 csv.DictReader 读取CSV文件的列名。
- 检查列是否存在: 确保要处理的列存在于CSV文件中。
- 确定列的索引: 获取要处理的列的索引。
- 定义处理函数: 定义replace_string_in_columns函数,该函数打开输入和输出CSV文件,并使用csv.reader和csv.writer读取和写入数据。
- 关键在于设置reader = csv.reader(infile, quoting=csv.QUOTE_NONE, delimiter=mydelimiter, quotechar='',escapechar='\\')和writer = csv.writer(outfile, quoting=csv.QUOTE_NONE, delimiter=mydelimiter, quotechar='',escapechar='\\'),这里quoting=csv.QUOTE_NONE禁用了引号,delimiter设置了分隔符,quotechar=''表示没有引号字符,escapechar='\\'用于转义分隔符。
- 在循环中,函数遍历每一行,并对指定列中的单元格进行字符串替换。
- 调用处理函数: 调用replace_string_in_columns函数来处理CSV文件。
- 替换文件: 用修改后的CSV文件替换原始CSV文件。
注意事项
- 务必仔细阅读csv模块的官方文档,了解每个参数的具体含义和用法。
- 在禁用引号时,要确保数据中不包含与delimiter冲突的字符,或者正确设置escapechar进行转义。
- 根据实际需求选择合适的quoting选项。
总结
通过正确设置csv.reader和csv.writer的参数,可以灵活地控制CSV文件的读写行为,避免不必要的引号,并实现各种复杂的文本处理需求。 在使用csv模块时,务必仔细阅读文档,理解每个参数的作用,才能编写出高效、稳定的代码。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《PythonCSV写入带引号数据的解决方法》文章吧,也可关注golang学习网公众号了解相关技术文章。
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
340 收藏
-
365 收藏
-
391 收藏
-
392 收藏
-
105 收藏
-
442 收藏
-
291 收藏
-
195 收藏
-
407 收藏
-
486 收藏
-
129 收藏
-
405 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习