user1781482 user1781482 - 11 months ago 86
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]:

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


instead of:

Answer Source

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'):


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