0

我一直在查看 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,会打印出一个包含每个条目的列表。我希望能够在每个条目通过迭代器时对其进行一次操作。所以我可以将每个条目保存在数据库中。关于如何做到这一点的任何建议?

4

2 回答 2

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

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

于 2013-07-25T03:00:23.403 回答
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

如果需要,您可以以比用 's 包围数据更复杂的方式操作数据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
于 2013-07-25T03:01:32.677 回答