将CSV行拆分为单独的字符串

时间:2013-07-25 02:51:08

标签: python csv

我一直在查看CSV文档,并且在迭代行中遇到了一些问题。如果有人可以清理它,那就太好了。例如,请使用以下代码:

custom_feature_string = 'Custom feature 1;custom feature, 2; Custom feature3; custom "feature" 4; customfeature5'
cfeature = StringIO.StringIO(custom_feature_string)
reader = csv.reader(cfeature, delimiter=';', skipinitialspace=True)
for row in reader:
    print '\n'.join(row)

现在,在将内容打印到屏幕上时,这一切都很好,但当我尝试用print '\n'.join(row)替换print row时,会打印出包含每个条目的列表。我希望能够在通过迭代器时操作每个条目一次。所以我可以将每个条目保存在数据库中。有关如何做到这一点的任何建议吗?

2 个答案:

答案 0 :(得分:1)

您的变量名称无法准确反映它们代表的内容。

reader = csv.reader(cfeature, delimiter=';', skipinitialspace=True)
for row in reader:
    print '\n'.join(row)
您的代码中的

row实际上是 CSV中所有行的列表。所以看看这个:

reader = csv.reader(cfeature, delimiter=';', skipinitialspace=True)
for data in reader:
    for row in data:
        #do something with row

然后,您将能够逐行处理它。

答案 1 :(得分:1)

您可以迭代row

import StringIO
import csv

custom_feature_string = 'Custom feature 1;custom feature, 2; Custom feature3; custom "feature" 4; customfeature5'
cfeature = StringIO.StringIO(custom_feature_string)
reader = csv.reader(cfeature, delimiter=';', skipinitialspace=True)
for row in reader:
    print '\n'.join(row)
    for item in row:
        print "X", item, "X"

这会产生:

Custom feature 1
custom feature, 2
Custom feature3
custom "feature" 4
customfeature5
X Custom feature 1 X
X custom feature, 2 X
X Custom feature3 X
X custom "feature" 4 X
X customfeature5 X

如果需要,您可以使用X的方式以更复杂的方式处理数据,例如将其插入数据库。您可以整体或分段操作行,并在每个段或该行的修改版本上插入一次数据库,或者按照您的喜好进行操作。


多行示例

import StringIO
import csv

custom_feature_string = 'Custom feature 1;custom feature, 2; Custom feature3; custom "feature" 4; customfeature5'

multiline = custom_feature_string + "\n" + custom_feature_string
cfeature = StringIO.StringIO(multiline)
reader = csv.reader(cfeature, delimiter=';', skipinitialspace=True)
for row in reader:
    print "New line"
    for item in row:
        print "X", item, "X"

输出

New line
X Custom feature 1 X
X custom feature, 2 X
X Custom feature3 X
X custom "feature" 4 X
X customfeature5 X
New line
X Custom feature 1 X
X custom feature, 2 X
X Custom feature3 X
X custom "feature" 4 X
X customfeature5 X