Issue
How do I create a list of strings in python where the strings can contain commas such that the interpreter doesn't break on commas prematurely.
I am reading in a template csv file, created by MSExcel. The contents are 2 columns: col1 = color, col2 = a sentence that can contain a comma. The content is as follows:
Light Green,"Matches type, instance, etc."
Red,Happens in BD10 but not BD20
Blue,"Instance and time matches, type doesn't match"
Yellow,Caught on replay
When I read in and output what was read, it breaks the input line on all commas.
#my code snippet, please excuse any typos during sanitization
with open('outfile.csv','r') as infile:
blah = infile.readlines()
for i in blah:
line = i.strip().split(",")
print line
My output:
['Light Green', '"Matches type', ' instance', ' etc."']
['Red', 'Happens in BD10 but not BD20']
['Blue', '"Instance and time matches', ' type doesn\'t match"']
['Yellow', 'Caught on replay']
How do I tell python to ignore commas when it's within "" and break at commas all other times?
Solution
Stop the split after the first comma:
line = i.strip().split(",", 1)
Answered By - Brent Washburne Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.