簡體   English   中英

將CSV行拆分為單獨的字符串

[英]Splitting a CSV row into separate strings

我一直在查看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 row替換print '\\n'.join(row)時,會打印出包含每個條目的列表。 我希望能夠在通過迭代器時操作每個條目一次。 所以我可以將每個條目保存在數據庫中。 有關如何做到這一點的任何建議?

您的變量名稱無法准確反映它們所代表的內容。

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

然后,您將能夠逐行處理它。

你可以遍歷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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM