将一列csv解压缩到逗号分隔的列表python中

时间:2015-01-09 07:34:13

标签: python csv split comma strip

我有一个CSV文件,如下所示:

with open ("ann.csv", "rb") as annotate:
    for col in annotate:
        ann = col.lower().split(",")
        print ann[0]

我的CSV文件如下所示:

H1,H2,H3
da,ta,one
dat,a,two

我的输出如下:

da
dat

但我想要一个逗号分隔的输出,如(da,dat)。我怎样才能做到这一点?如果你在downvoting之前给我一个想法,我真的很感激。

6 个答案:

答案 0 :(得分:5)

首先,在Python中你有csv module - 使用它。

其次,您正在遍历行,因此使用col作为变量名称有点令人困惑。

第三,只需收集列表中的项目并使用.join()打印:

import csv
with open ("ann.csv", "rb") as csvfile:
    reader = csv.reader(csvfile)
    reader.next() # Skip the header row
    collected = []
    for row in reader:
        collected.append(row[0])
    print ",".join(collected)

答案 1 :(得分:3)

尝试这样:

with open ("ann.csv", "rb") as annotate:
    output = []
    next(annotate)    # next will advanced the file pointer to next line
    for col in annotate:
        output.append(col.lower().split(",")[0])
    print ",".join(output)

答案 2 :(得分:2)

不是在现场打印,而是构建一个字符串,然后将其打印出来。

s = ''
with open ("ann.csv", "rb") as annotate:
    for col in annotate:
        ann = col.lower().split(",")
        s += ann[0] + ','
s = s[:-1] # Remove last comma
print(s)

我还建议更改变量名称col,它是在行上循环,而不是在列上循环。

答案 3 :(得分:2)

然后试试这个:

result = ''
with open ("ann.csv", "rb") as annotate:
    for col in annotate:
        ann = col.lower().split(",")
        # add first element of every line to one string and separate them by comma
        result = result + ann[0] + ','

print result        

答案 4 :(得分:2)

试试这个

>>> with open ("ann.csv", "rb") as annotate:
...     for col in annotate:
...         ann = col.lower().split(",")
...         print ann[0]+',',
... 

答案 5 :(得分:1)

使用numpy.loadtxt可能会更容易一些:

In [23]: import numpy as np
    ...: fn = 'a.csv'
    ...: m = np.loadtxt(fn, dtype=str, delimiter=',')
    ...: print m
[['H1' 'H2' 'H3']
 ['da' 'ta' 'one']
 ['dat' 'a' 'two']]

In [24]: m[:,0][1:]
Out[24]: 
array(['da', 'dat'], 
      dtype='|S3')

In [25]: print ','.join(m[:,0][1:])
da,dat

m[:,0]获取矩阵m的第一列,[1:]跳过第一个元素'H1'