Home > Software engineering >  How to deal with a delimiter (;) at the end of each line?
How to deal with a delimiter (;) at the end of each line?

Time:12-22

I have a CSV file with a ; as the delimiter. However, each line ends with a the delimiter as well. Like this:

A1;A2;A3;
B1;B2;B3;
C1;C2;C3;

Thus, my code ..

import csv

f = open('test.csv', 'r', newline='')
content = csv.DictReader(f, delimiter=';')
for element in content:
    print(element)
f.close()

.. believes that there are four values per line, with the last one being empty.

That can't be intended. Am I doing something wrong?
Is there a more elegant way to deal with this than having to delete the last value of each line?

CodePudding user response:

Your question is similar but not the same as this one. There, the data is spat-out on one line with a special character used as new-line. Your problem is different as you have a file with lines but with an extra delimiter.

I couldn't find a built-in way to handle this with the csv module (trying to do newline=';' in the open raises an error). So similar to the accepted answer in the linked question, we can manipulate each line of the file before reading it as a CSV:

import csv

def lines_generator(file):
    for line in file:
        yield line.rstrip(';\n')

with open("test.csv", "r") as myfile:
    content = csv.DictReader(lines_generator(myfile), delimiter=';')
    for element in content:
        print(element)
  • Related