user1781482
user1781482

Reputation: 633

Python 3.5 CSV reading multiline field issue

I am trying to parse a CSV file, which has multi-line string in one of the fields (field 6). I can read the field fine, but when I try to process each line from that field, it gives me one character on a new line at a time instead of a line at a time. Any ideas what am I doing wrong?

def lookup(ip, ranges_csv):
    with open(ranges_csv, 'r') as csvIN:
        l = csv.reader(csvIN, dialect='excel')
        next(l)  # Skip the header row

        for row in l:
            for subnet in row[5]:
                print(subnet)

Let's say in field6 we have 192.168.0.0/24 and 192.168.1.0/24 each on newline. I'm getting this output:

1
9
2
.
1
6
8

instead of:

192.168.0.0/24
192.168.1.0/24

Upvotes: 0

Views: 224

Answers (2)

DorElias
DorElias

Reputation: 2313

well it makes sense, since each element in row is a string, and when you iterate a string you get one character at a time.

you can split the string to get your desired result:

for row in l:
    for subnet in row[5].split('\r\n'):
        print(subnet)

note:

\r\n means new line in windows, if you are using linux it should be only \n.

Upvotes: 2

Nf4r
Nf4r

Reputation: 109

When you are using

for subnet in row[5]:

   print(subnet)

You are iterating over a string, which returns a single char each time.

It would be more helpful if you could give us an example to see exactly what do you mean.

Upvotes: 0

Related Questions