2

I need to merge vertically the data from several CSV spreadsheets in Python. Their structure is identical, I just need to put one table's data on top of the following because they are the months on an annual survey. I tried several methods I found googling but I can't find a way to do something as simple as:

import csv

spreadsheets1 = open('0113_RE_fscom.csv','r')
spreadsheets2 = open('0213_RE_fscom.csv','r')
spreadsheets = spreadsheets1 + spreadsheets2

with spreadsheet as csvfile:
   sales = csv.reader(csvfile)
   for row in sales:
      print row

3 Answers 3

2

Looks like you simply forgot to iterate over files. Try this code:

import csv

spreadsheet_filenames = [
    '0113_RE_fscom.csv',
    '0213_RE_fscom.csv',
]

for filename in spreadsheet_filenames:
    with open(filename, 'r') as csvfile:
        sales = csv.reader(csvfile)
        for row in sales:
            print row
Sign up to request clarification or add additional context in comments.

Comments

0

how about this:

import csv
from itertools import izip

with open('0113_RE_fscom.csv', 'r') as f1, open('0113_RE_fscom.csv', 'r') as f2:
   csv1 = csv.reader(f1, delimiter=',')
   csv2 = csv.reader(f2, delimiter=',')
   for line1, line2 in izip(csv1, csv2):
      print line1 + line2

Comments

0

This is quite simple with pandas.

import pandas as pd
f1 = pd.read_csv('0113_RE_fscom.csv', header=None)
f2 = pd.read_csv('0213_RE_fscom.csv', header=None)
merged = pd.concat(f1, f2)
merged.to_csv('merged.csv', index=None, header=None)

Remove header=None if your files actually do have a header.

Comments

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.