0

I'm very new to Python. I don't have a strong handle on all of the vocabulary.

My current task includes leading data from a CSV file in the format of:

row1data1,row1data2,row1data3
row2data1,row2data2,row2data3
etc.

From what I've gathered, the csv.reader/csvfile built-in module creates a single string from each row. I need two strings from each row, with the comma being the delimiter.

This is the my current code and output.

CODE:

import csv
with open('Sparrow.csv', 'r') as csvfile:
    CSVReader = csv.reader(csvfile, quotechar='|')
    for row in CSVReader:
       print( "TEXT" )
       print( "\n" )
       print( "TEXT INPUT REQUIRED:'%s'" % " ".join(row))
       print( "\n" )
       print( "TEXT INPUT REQUIRED:'%s'" % " ".join(row))
       print( "\n" )
       print( "TEXT" )       
       print( "\n" )
       print( "('%s'));" % " ".join(row))
       print( "\n" )
       print( "\n" )

OUTPUT

TEXT
TEXT INPUT REQUIRED:'row1data1 row1data2 row1data3'
TEXT INPUT REQUIRED:'row1data1 row1data2 row1data3'
TEXT
('row1data1 row1data2 row1data3'));


TEXT
TEXT INPUT REQUIRED:'row2data1 row2data2 row2data3'
TEXT INPUT REQUIRED:'row2data1 row2data2 row2data3'
TEXT
('row2data1 row2data2 row2data3'));

Again, to clarify, I need to split the strings so the output is as displayed below.

TEXT
TEXT INPUT REQUIRED:'row1data1'
TEXT INPUT REQUIRED:'row1data2'
TEXT
('row1data3'));


TEXT
TEXT INPUT REQUIRED:'row2data1'
TEXT INPUT REQUIRED:'row2data2'
TEXT
('row2data3'));

I know this is something very easy that I'm missing and any help would be appreciated.

4

2 回答 2

0

That should do it:

print( "TEXT" )
print( "\n" )
for i in range(1):
    print "TEXT INPUT REQUIRED:'%s'" % row[i]
print( "\n" )
print( "('%s'));" % row[2]
于 2013-10-23T17:36:44.267 回答
0

Split the line before printing it

for row in CSVReader:
    a,b,c = row.split(',')
    print( "TEXT\n" )
    print( "TEXT INPUT REQUIRED:'%s'\n" % " ".join(a))
    print( "TEXT INPUT REQUIRED:'%s'\n" % " ".join(b))
    print( "TEXT\n" )       
    print( "('%s'));\n\n" % " ".join(c))
于 2013-10-23T17:37:43.407 回答