Home > Software engineering >  how to append a column from a csv file to another csv file without using panda?
how to append a column from a csv file to another csv file without using panda?

Time:07-31

I want to append a column from 'b.csv' file and put it into 'a.csv' file but it only add a letter and not the whole string. I tried searching in google but there's no answer. I want to put the column under the headline "number". This is my code:

f = open('b.csv')
default_text = f.read()
with open('a.csv', 'r') as read_obj, \
        open('output_1.csv', 'w', newline='') as write_obj:
    csv_reader = reader(read_obj)
    csv_writer = writer(write_obj)
    for row in csv_reader:
        row.append(default_text[8])
        csv_writer.writerow(row)

This is the info in 'a.csv'

name,age,course,school,number
Leo,18,BSIT,STI
Rommel,23,BSIT,STI
Gaby,33,BSIT,STI
Ranel,31,BSIT,STI

This is the info in 'b.csv'

1212121
1094534
1345684
1093245

CodePudding user response:

You can just concat rows read from both CSV file and pass it immediately to writer:

import csv
from operator import concat

with open(r'a.csv') as f1, \
        open(r'b.csv') as f2, \
        open(r'output_1.csv', 'w', newline='') as out:
    f1_reader = csv.reader(f1)
    f2_reader = csv.reader(f2)
    writer = csv.writer(out)
    writer.writerow(next(f1_reader))  # write column names
    writer.writerows(map(concat, f1_reader, f2_reader))

So we initialize csv.reader() for both CSV files and csv.writer() for output. As first file (a.csv) contains column names, we read it using next() and pass to .writerow() to write them into output without any modifications. Then using map() we can iterate over both readers simultaneously applying operator.concat() which concatenate rows returned from both reader. We can pass it directly to .writerows() and let it consume generator returned by map().


You can help my country, check my profile info.

CodePudding user response:

If only pandas cannot be used, then it's convenient to use Table helper from convtools library (github).

from convtools.contrib.tables import Table
from convtools import conversion as c

(
    Table.from_csv("tmp/1.csv", header=True)
    # this step wouldn't be needed if your first file wouldn't have missing
    # "number" column
    .drop("number")
    .zip(Table.from_csv("tmp/2.csv", header=["number"]))
    .into_csv("tmp/results.csv")
)
  • Related