user1781482 user1781482 - 3 months ago 27
Python Question

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

Answer

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.