首页 > 解决方案 > 如何修复这个 qouting 在 python 中读取 csv 文件时必须是整数

问题描述

def read_csv_fieldnames(filename, separator, quote):
    """
    Inputs:
      filename  - name of CSV file
      separator - character that separates fields
      quote     - character used to optionally quote fields
    Ouput:
      A list of strings corresponding to the field names in
      the given CSV file.
    """

    with open(filename, newline="") as csv_file:
        row_fieldnames = []
        reader = csv.reader(csv_file, delimiter=separator, quoting=quote)
        for row in reader:
            row_fieldnames.append(row)

    return row_fieldnames[0]


test_file1 = read_csv_fieldnames("table1.csv", ',', '"')

这是我的 csv 文件 Table1.csv = Field1,Field2,Field3,Field4 中的数据

预期输出 = ['Field1', 'Field2', 'Field3', 'Field4']

运行代码后=TypeError,引用必须是整数

标签: python

解决方案


quote - 用于可选地引用字段的字符

是的,但是您将其传递给了quoting此处的参数:

reader = csv.reader(csv_file, delimiter=separator, quoting=quote)

然而quoting 需要一个整数。要指定引号字符,请使用quotechar参数


推荐阅读