Python - 使用CSV文件输入/拆分字符串

时间:2013-10-23 17:32:31

标签: python string csv input

我是Python的新手。我对所有词汇都没有很强的把握。

我当前的任务包括以CSV格式导出CSV文件中的数据:

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

从我收集的内容来看,csv.reader / csvfile内置模块会从每一行创建一个字符串。我需要每行两个字符串,逗号是分隔符。

这是我目前的代码和输出。

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" )

输出

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

再次,为了澄清,我需要拆分字符串,以便输出如下所示。

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


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

我知道这很容易,我很遗憾,任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

应该这样做:

print( "TEXT" )
print( "\n" )
for i in range(1):
    print "TEXT INPUT REQUIRED:'%s'" % row[i]
print( "\n" )
print( "('%s'));" % row[2]

答案 1 :(得分:0)

在打印之前拆分线

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