0

How can I transpose the ouput of many rows to one row which is comma separated?

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

Current Output - Many Rows:

abc
def
ghi
jkl

Desired Output - One Row, Comma Separated:

abc,def,ghi,jkl

1 Answer 1

1

In python 2.x, to suppress the automatic newline of print, add a trailing , (comma). Now a space will be used instead of a newline.

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

In python 3.x, add end=' ' argument:

with open(filein, 'r') as rh:
    for line in rh:
        clm = line.split(',')[0] #Returns first column
        print(clm, end=',')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.