Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9202313
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T23:13:37+00:00 2026-06-17T23:13:37+00:00

I have a bunch of CSV files (only two in the example below). Each

  • 0

I have a bunch of CSV files (only two in the example below). Each CSV file has 6 columns. I want to go into each CSV file, copy the first two columns and add them as new columns to an existing CSV file.

Thus far I have:

import csv

f = open('combined.csv')
data = [item for item in csv.reader(f)]
f.close()

for x in range(1,3): #example has 2 csv files, this will be automated
    n=0
    while n<2:
        f=open(str(x)+".csv")
        new_column=[item[n] for item in csv.reader(f)]
        f.close()
        #print d

        new_data = []

        for i, item in enumerate(data):
            try:
                item.append(new_column[i])
                print i
            except IndexError, e:
                item.append("")
            new_data.append(item)

        f = open('combined.csv', 'w')
        csv.writer(f).writerows(new_data)
        f.close()
        n=n+1

This works, it is not pretty, but it works.
However, I have three minor annoyances:

  1. I open each CSV file twice (once for each column), that is hardly elegant

  2. When I print the combined.csv file, it prints an empty row following each row?

  3. I have to provide a combined.csv file that has at least as many rows in it as the largest file I may have. Since I do not really know what that number may be, that kinda sucks

As always, any help is much appreciated!!

As requested:
1.csv looks like (mock data)

1,a
2,b
3,c
4,d

2.csv looks like

5,e
6,f
7,g
8,h
9,i

the combined.csv file should look like

1,a,5,e
2,b,6,f
3,c,7,g
4,d,8,h
,,9,i
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T23:13:38+00:00Added an answer on June 17, 2026 at 11:13 pm
    import csv
    import itertools as IT
    
    filenames = ['1.csv', '2.csv']
    handles = [open(filename, 'rb') for filename in filenames]    
    readers = [csv.reader(f, delimiter=',') for f in handles]
        
    with  open('combined.csv', 'wb') as h:
        writer = csv.writer(h, delimiter=',', lineterminator='\n', )
        for rows in IT.izip_longest(*readers, fillvalue=['']*2):
            combined_row = []
            for row in rows:
                row = row[:2] # select the columns you want
                if len(row) == 2:
                    combined_row.extend(row)
                else:
                    combined_row.extend(['']*2)#This extends two empty columns
            writer.writerow(combined_row)
            
    for f in handles:
        f.close()
    

    The line for rows in IT.izip_longest(*readers, fillvalue=['']*2):
    can be understood with an example:

    In [1]: import itertools as IT
    
    In [2]: readers = [(1,2,3), ('a','b','c','d'), (10,20,30,40)]
    
    In [3]: list(IT.izip_longest(readers[0], readers[1], readers[2]))
    Out[3]: [(1, 'a', 10), (2, 'b', 20), (3, 'c', 30), (None, 'd', 40)]
    

    As you can see, IT.izip_longest behaves very much like zip, except that it does not stop until the longest iterable is consumed. It fills in missing items with None by default.

    Now what happens if there were more than 3 items in readers?
    We would want to write

    list(IT.izip_longest(readers[0], readers[1], readers[2], ...))
    

    but that’s laborious and if we did not know len(readers) in advance, we wouldn’t even be able to replace the ellipsis (...) with something explicit.

    Python has a solution for this: the star (aka argument unpacking) syntax:

    In [4]: list(IT.izip_longest(*readers))
    Out[4]: [(1, 'a', 10), (2, 'b', 20), (3, 'c', 30), (None, 'd', 40)]
    

    Notice the result Out[4] is identical to the result Out[3].

    The *readers tells Python to unpack the items in readers and send them along as individual arguments to IT.izip_longest.
    This is how Python allows us to send an arbitrary number of arguments to a function.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a bunch of csv files. Each has data from a different period:
I have to read a bunch of .CSV files with dynamic file names from
I loaded a bunch of CSV files into R. I have questions about how
I have two .csv files, headers.csv and corrected.csv . The headers.csv has all the
I have a folder that contains a bunch of csv files and I want
I have a bunch of CSV files to import and so I've created BCPFORMAT
I have a bunch of csv datasets, about 10Gb in size each. I'd like
I have a code that writes a bunch of lines to csv files. It
I have a csv file that contains a bunch of states in one column
I have a bunch of CSV files. In some of them, missing data are

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.