Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read unstructured CSV

Tags:

python

csv

I want to parse a given csv file, that looks like

"header_1" ; "header_2"; "header_3"
"a" ; "b" ; "c"
"1" ; "2" ; "3"

Some footer text; maybe more.

Only well and correct structured fields shall be parsed. How can I enforce that?

The following code does the job:

with open(path) as csv_file:
    reader = csv.reader(csv_file, delimiter=";", strict=False)
    result = []
    for row in reader:
        if row == []:
            break
        result += [row]

Is there a smarter, pythonic solution without checking the line if it is empty or not? In general, I would prefer DictReader.

like image 741
Michael Dorner Avatar asked Sep 13 '26 21:09

Michael Dorner


1 Answers

Instead of using break you can use the fact that empty lists evaluate to false and use a while loop instead:

while row in reader:
    result.append(row)
like image 145
Si Kelly Avatar answered Sep 16 '26 10:09

Si Kelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!