Home > Enterprise >  Python CSV different delimiter
Python CSV different delimiter

Time:01-10

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.

with open("data.csv", "r") as data:
    for line in data:
        for line.split('`') as element:
            print(element)

example input file:

sarah`120`18kg`22Rep
thomas`160`8kg`11Rep

the expected out should be:

sarah
120
18kg
22Rep
thomas
160
8kg
11Rep

but this is what I get:




Thanks for your time!

CodePudding user response:

I'd suggest using the DictReader class from the standard library like so:

import csv

def read_csv(filepath: str) -> list:
    """Read csv file from given path, return contents as list of dictionaries"""
    with open(filepath, encoding='utf-8') as f:
        r = csv.DictReader(f, delimiter='`')
        return list(r)

print(read_csv("data.csv"))

CodePudding user response:

Maybe try a python csv library called pandas.

I found a tutorial that shows you how to use custom delimiters.

pandas.read_csv(filepath_or_buffer, sep=', ', delimiter=None, header='infer', names=None, index_col=None, ....)

I think this line will be most useful to you.

CodePudding user response:

I haven't had a chance to test this but your loop on all of the elements looks incorrect. Try:

with open("data.csv", "r") as data:
    for line in data:
        for element in line.split('`'):
            print(element)
  •  Tags:  
  • Related