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.
读取以钟形字符作为分隔符的CSV文件时,出现类型错误。我不想使用熊猫,我需要使用CSV库来解决这个问题。
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
铃声字符参考-https://www.asciihex.com/character/control/7/0x07/bel-bell-alert
更多回答
优秀答案推荐
you're using the raw prefix for your \a
delimiter, which makes it 2 characters (backslash, then a
)
您使用了原始前缀作为您的\a分隔符,这使其成为2个字符(反斜杠,然后是a)
You need to just use delimiter='\a'
, 1 character, the one which is needed to separate the fields.
您只需要使用DELIMITER=‘\a’,1个字符,这是分隔字段所需的字符。
>>> len(r'\a')
2
>>> len('\a')
1
>>>
更多回答
我是一名优秀的程序员,十分优秀!