简体   繁体   中英

Remove an empty row from a CSV

I have a csv made like this:

16;SILCOMP1;1;;;;;A;;;;;;;GO_SLAVE_10;niente
32;SILCOMP1;1;;;;A;;;;;;;;GO_SLAVE_10;niente
64;SILCOMP1;1;;A;;;;;;;;;;GO_SLAVE_10;niente
128;SILCOMP1;1;A;;;;;;;;;;;GO_SLAVE_10;niente
;;;;;;;;;;;;;;;
3;SILCOMP1;2;;;;;;;;;;B;A;niente;niente
5;SILCOMP1;2;;;;;;;;B;;;A;niente;niente

basically I want to create a code that automaticaly recognize the row ";;;;"the one between 128 and 3 and delete or skip it. After moving each raw of the csv into a data_array, I've tried to use the

len(data_array[i]) == 0

but it seems that even if the raw is made by ";"it is not empty. Any idea?

With a file data.csv like

16;SILCOMP1;1;;;;;A;;;;;;;GO_SLAVE_10;niente
32;SILCOMP1;1;;;;A;;;;;;;;GO_SLAVE_10;niente
64;SILCOMP1;1;;A;;;;;;;;;;GO_SLAVE_10;niente
128;SILCOMP1;1;A;;;;;;;;;;;GO_SLAVE_10;niente
;;;;;;;;;;;;;;;
3;SILCOMP1;2;;;;;;;;;;B;A;niente;niente
5;SILCOMP1;2;;;;;;;;B;;;A;niente;niente

this

import csv

with open("data.csv", "r") as file:
    data = [
        row for row in csv.reader(file, delimiter=";")
        if any(item != "" for item in row)
    ]

does produce the following data :

[['16', 'SILCOMP1', '1', '', '', '', '', 'A', '', '', '', '', '', '', 'GO_SLAVE_10', 'niente']
 ['32', 'SILCOMP1', '1', '', '', '', 'A', '', '', '', '', '', '', '', 'GO_SLAVE_10', 'niente']
 ['64', 'SILCOMP1', '1', '', 'A', '', '', '', '', '', '', '', '', '', 'GO_SLAVE_10', 'niente']
 ['128', 'SILCOMP1', '1', 'A', '', '', '', '', '', '', '', '', '', '', 'GO_SLAVE_10', 'niente']
 ['3', 'SILCOMP1', '2', '', '', '', '', '', '', '', '', '', 'B', 'A', 'niente', 'niente']
 ['5', 'SILCOMP1', '2', '', '', '', '', '', '', '', 'B', '', '', 'A', 'niente', 'niente']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM