1

I have an issue where I am reading a csv file as a file ( easier for me to get results that reading as csv) that is exported from an application. I have my code working to read that file and import it into a list. Then I iterate through the list and save to the appropriate fields. I am using the built in method .split(',') and it works great to a point. I am able to get my colors the way I want but all the way down on line 70 is were my mistake occurs. I am found that due to a certain field has multiple lines is causing the program to import each line into the list and creating a column for each line. How can I ignore a filed that has multiple lines when trying to do a split?

jmcnamara
  • 38,196
  • 6
  • 90
  • 108

2 Answers2

0

You can get rid of the newlines in the field by doing a string .replace('\n', ' ') on it.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

I am found that due to a certain field has multiple lines is causing the program to import each line into the list and creating a column for each line. How can I ignore a filed that has multiple lines when trying to do a split?

Rather than trying to parse the file yourself, and having to deal with edge cases, you should just use the core csv module.

Say you have some data like this:

 +----------+-----------+----------+
 | Aaa      | Bbb       | Ccc      |
 +---------------------------------+
 | 1        | 2         | 3        |
 +---------------------------------+
 | Foo      | Bar       | Goo      |
 |          | Baz       |          |
 |          | Bag       |          |
 +---------------------------------+
 | 5        | 6         | 7        |
 +----------+-----------+----------+

Which is exported to a CSV file like this:

$cat test_file.csv
Aaa,Bbb,CCC
1,2,3
Foo ,"Bar
Baz
Bag",Goo
5,6,7

You can easily read this in as follows:

import csv

with open('test_file.csv', 'rb') as csvfile:
    csv_reader = csv.reader(csvfile)
    for row in csv_reader:
        print row

Gives:

$python test_reader.py

['Aaa', 'Bbb', 'CCC']
['1', '2', '3']
['Foo ', 'Bar\nBaz\nBag', 'Goo']
['5', '6', '7']
jmcnamara
  • 38,196
  • 6
  • 90
  • 108
  • Yeah that may be the way to go and then convert that to xlsx so I can add all my fancy coloring. I will do my homework on csv. Thanks Bud! – user1385511 Mar 18 '15 at 18:45