英文:
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
>>>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论