将列转置为行 - python

时间:2015-07-16 17:09:53

标签: python-3.x

如何将多行的输出转换为逗号分隔的一行?

with open(filein, 'r') as rh:
    for line in rh:
        clm = line.split(',')[0] #Returns first column
        print(clm)

电流输出 - 许多行:

abc
def
ghi
jkl

所需输出 - 一行,逗号分隔:

abc,def,ghi,jkl

1 个答案:

答案 0 :(得分:1)

在python 2.x中,要禁止打印的自动换行,请添加尾随,(逗号)。现在将使用一个空格而不是换行符。

with open(filein, 'r') as rh:
    for line in rh:
        clm = line.split(',')[0] #Returns first column
        print clm, ',',

在python 3.x中,添加end =''参数:

with open(filein, 'r') as rh:
    for line in rh:
        clm = line.split(',')[0] #Returns first column
        print(clm, end=',')