
本文旨在解决在使用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: 指定字段之间的分隔符。 默认为逗号 (,)。
立即学习“Python免费学习笔记(深入)”;
quotechar: 指定包围含有特殊字符(例如 delimiter)的字段的字符。 默认为双引号 (")。
escapechar: 用于转义 quotechar 的字符。
quoting: 控制何时应用引号。 常用的选项包括:
以下代码展示了如何使用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:
File columns names: {}
Input 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:
", result)代码解释:
通过正确设置csv.reader和csv.writer的参数,可以灵活地控制CSV文件的读写行为,避免不必要的引号,并实现各种复杂的文本处理需求。 在使用csv模块时,务必仔细阅读文档,理解每个参数的作用,才能编写出高效、稳定的代码。
以上就是解决Python CSV写入时引号问题:csv.writer参数详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号