解决Python CSV写入时引号问题:csv.writer参数详解

解决Python CSV写入时引号问题:csv.writer参数详解

本文旨在解决在使用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.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: 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)

代码解释:

  1. 导入必要的模块: 导入csv, io, os 和 shutil 模块。
  2. 定义参数: 定义CSV文件路径、需要处理的列名、要替换的字符串、替换后的字符串以及分隔符。
  3. 文件检查: 检查CSV文件是否存在,以及分隔符是否存在于第一行中。
  4. 读取列名: 使用 csv.DictReader 读取CSV文件的列名。
  5. 检查列是否存在: 确保要处理的列存在于CSV文件中。
  6. 确定列的索引: 获取要处理的列的索引。
  7. 定义处理函数: 定义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=”用于转义分隔符。
    • 循环中,函数遍历每一行,并对指定列中的单元格进行字符串替换。
  8. 调用处理函数: 调用replace_string_in_columns函数来处理CSV文件。
  9. 替换文件: 用修改后的CSV文件替换原始CSV文件。

注意事项

  • 务必仔细阅读csv模块的官方文档,了解每个参数的具体含义和用法。
  • 在禁用引号时,要确保数据中不包含与delimiter冲突的字符,或者正确设置escapechar进行转义。
  • 根据实际需求选择合适的quoting选项。

总结

通过正确设置csv.reader和csv.writer的参数,可以灵活地控制CSV文件的读写行为,避免不必要的引号,并实现各种复杂的文本处理需求。 在使用csv模块时,务必仔细阅读文档,理解每个参数的作用,才能编写出高效、稳定的代码。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享