Julien
Julien

Reputation: 629

Add a column from a csv to another csv

I have 2 files named input.csv (composed of one column count ) and output.csv (composed of one column id).
I want to paste my count column in output.csv, just after the id column.

Here is my snippet :

with open ("/home/julien/input.csv", "r") as csvinput:
    with open ("/home/julien/excel/output.csv", "a") as csvoutput:
        writer = csv.writer(csvoutput, delimiter = ";")

        for row in csv.reader(csvinput, delimiter = ";"):
            if row[0] != "":
                result = row[0]
            else:
                result = ""  

             row.append(result)
         writer.writerow(row)

But it doesn't work.

I've been searching the problem for many hours but I'v got no solution. Would you have any tricks to solve my problem ?
Thanks! Julien

Upvotes: 1

Views: 4306

Answers (3)

chfw
chfw

Reputation: 4592

If anyone was given two tables, merging them by using first column of each is very easy. With my library pyexcel, you do the merge just like merging tables:

>>> from pyexcel import Reader,Writer
>>> f1=Reader("input.csv", delimiter=';')
>>> f2=Reader("output.csv", delimiter=';')
>>> columns = [f1.column_at(0), f2.column_at(0)]
>>> f3=Writer("merged.csv", delimiter=';')
>>> f3.write_columns(columns)
>>> f3.close()

Upvotes: 0

Mike Müller
Mike Müller

Reputation: 85582

You need to work with three files, two for reading and one for writing. This should work.

import csv

in_1_name = "/home/julien/input.csv"
in_2_name = "/home/julien/excel/output.csv"
out_name = "/home/julien/excel/merged.csv"

with open(in_1_name) as in_1, open(in_2_name) as in_2, open(out_name, 'w') as out:
    reader1 = csv.reader(in_1, delimiter=";")
    reader2 = csv.reader(in_2, delimiter=";")
    writer = csv.writer(out, delimiter=";")
    for row1, row2 in zip(reader1, reader2):
        if row1[0] and row2[0]:
            writer.writerow([row1[0], row2[0]])

You write the row for each column:

            row.append(result)
            writer.writerow(row)

Dedent the last line to write only once:

            row.append(result)
        writer.writerow(row)

Upvotes: 1

STLDev
STLDev

Reputation: 6174

  1. Open both files for input.
  2. Open a new file for output.
  3. In a loop, read a line from each, formatting an output line, which is then written to the output file
  4. close all the files
  5. Programmatically copy your output file on top of the input file "output.csv".

Done

Upvotes: 1

Related Questions