将csv的一列提取到逗号分隔的列表python中

2024-05-18 22:29:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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)。我该怎么做?如果你能在投票前给我一个主意,我会非常感激的。


Tags: 文件csvinforaswithcolopen
3条回答

首先,在Python中有^{} 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)

像这样试试:

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)

然后试试这个:

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        

相关问题 更多 >

    热门问题