PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 28, 2022

[FIXED] how to append a column from a csv file to another csv file without using panda?

 August 28, 2022     csv, python     No comments   

Issue

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

Solution

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.



Answered By - Olvin Roght
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing