0

I am new to pyhton and am stuck on this topic from 2 days,tried looking for a basic answer but couldn't,so finally I decided to come up with my question.

I want to concatenate the values of only first two rows of my csv file(if possible with help of inbuilt modules). Any kind of help would be appreciated. Thnx in advance

Below is my sample csv file without headers:

1,Suraj,Bangalore

2,Ahuja,Karnataka

3,Rishabh,Bangalore

Desired Output:

1 2,Suraj Ahuja,Bangalore Karnataka

3,Rishabh,Bangalore
2
  • 1
    Did you try writing something? Where precisely are you stuck? Commented Jan 20, 2017 at 9:37
  • Provided you already know how to read and write csv data, you can combine python lists and the zip() function to achieve what you want. Commented Jan 20, 2017 at 9:56

3 Answers 3

2

Just create a csv.reader object (and a csv.writer object). Then use next() on the first 2 rows and zip them together (using list comprehension) to match the items.

Then process the rest of the file normally.

import csv

with open("file.csv") as fr, open("output.csv","w",newline='') as fw:
    cr=csv.reader(fr)
    cw=csv.writer(fw)
    title_row = [" ".join(z) for z in zip(next(cr),next(cr))]
    cw.writerow(title_row)
    # dump the rest as-is
    cw.writerows(rows)

(you'll get an exception if the file has only 1 row of course)

Sign up to request clarification or add additional context in comments.

Comments

1

You can use zip() for your first 2 lines like below:

with open('f.csv') as f:
    lines = f.readlines()
    res = ""
    for i, j in zip(lines[0].strip().split(','), lines[1].strip().split(',')):
        res += "{} {},".format(i, j)
    print(res.rstrip(','))
    for line in lines[2:]:
        print(line)

Output:

1 2,Suraj Ahuja,Bangalore Karnataka
3,Rishabh,Bangalore

2 Comments

Thnx for the . Really Appreciate it . It Worked
@SurajAhuja You're welcome to SOF. Please, check this link to see how to accept an answer stackoverflow.com/help/someone-answers
1
with open('file2', 'r') as f, open('file2_new', 'w') as f2:
    lines = [a.split(',') for a in f.read().splitlines() if a.strip()]
    newl2 = [[' '.join(x) for x in zip(lines[0], lines[1])]] + lines[2:]
    for a in newl2:
        f2.write(', '.join(a)+'\n')

1 Comment

Although this code might solve the problem, one should always consider adding an explanation to it.

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.