TypeError – 读取 CSV 功能

huangapple go评论72阅读模式
英文:

TypeError - read csv functionality

问题

reader = csv.DictReader(file, delimiter='\a', quoting=csv.QUOTE_ALL, skipinitialspace=True, fieldnames=columns)
英文:

I am getting a Type error when reading a csv file with a bell character as a separator. I don't want to use the pandas and need to utilize the csv libraries for this issue.

Sample header:

["header1", "header2", "header3"]

Data types

[integer, string, integer]

Sample data:

"2198"^G"data"^G"x"
"2199"^G"data2"^G"y"
"2198"^G"data3"^G"z"

Sample code

def main():
    columns = ['col1', 'col2', 'col3']
    try:
        csv_dict_list = []
        with open("bell.csv", "r") as file:
            reader = csv.DictReader(file, delimiter=r'\a', quoting=csv.QUOTE_ALL, skipinitialspace=True, fieldnames=columns)
            for row in reader:
                print(row)
                csv_dict_list.append(row)
    except Exception as e:
        raise Exception("Unable to read file: %s" % e)

I get this error -

TypeError: "delimiter" must be a 1-character string

Bell character reference - https://www.asciihex.com/character/control/7/0x07/bel-bell-alert

答案1

得分: 0

你正在使用原始前缀\a来定义你的分隔符,这会使其变成2个字符(反斜杠,然后是a)。

你只需要使用delimiter='\a',1个字符,用于分隔字段。

>>> len(r'\a')
2
>>> len('\a')
1
>>>
英文:

you're using the raw prefix for your \a delimiter, which makes it 2 characters (backslash, then a)

You need to just use delimiter='\a', 1 character, the one which is needed to separate the fields.

>>> len(r'\a')
2
>>> len('\a')
1
>>>

huangapple
  • 本文由 发表于 2023年5月22日 03:59:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定