I am trying to read a file that has ` as delimiters. I have tried some of the other solutions for a different delimiter but none seemed to work.
JavaScript
x
5
1
with open("data.csv", "r") as data:
2
for line in data:
3
for line.split('`') as element:
4
print(element)
5
example input file:
JavaScript
1
3
1
sarah`120`18kg`22Rep
2
thomas`160`8kg`11Rep
3
the expected out should be:
JavaScript
1
9
1
sarah
2
120
3
18kg
4
22Rep
5
thomas
6
160
7
8kg
8
11Rep
9
but this is what I get:
JavaScript
1
3
1
2
3
Thanks for your time!
Advertisement
Answer
I’d suggest using the DictReader class from the standard library like so:
JavaScript
1
10
10
1
import csv
2
3
def read_csv(filepath: str) -> list:
4
"""Read csv file from given path, return contents as list of dictionaries"""
5
with open(filepath, encoding='utf-8') as f:
6
r = csv.DictReader(f, delimiter='`')
7
return list(r)
8
9
print(read_csv("data.csv"))
10