TypeError – 读取 CSV 功能

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

TypeError - read csv functionality

问题

  1. 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:

  1. ["header1", "header2", "header3"]

Data types

  1. [integer, string, integer]

Sample data:

  1. "2198"^G"data"^G"x"
  2. "2199"^G"data2"^G"y"
  3. "2198"^G"data3"^G"z"

Sample code

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

I get this error -

  1. 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个字符,用于分隔字段。

  1. >>> len(r'\a')
  2. 2
  3. >>> len('\a')
  4. 1
  5. >>>
英文:

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.

  1. >>> len(r'\a')
  2. 2
  3. >>> len('\a')
  4. 1
  5. >>>

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:

确定