-2

I have two csv files named x.csv and y.csv. x.csv has only one row - Column A:0, Column B:1, Column C:2, Column D:3. In y.csv, only one row - Column A:2, Column B:3, Column C:4. I need to find the difference of the two csv files using python and output to a third csv file.

So far I have tried with open('x.csv','rb') as f1, open('y.csv','rb') as f2

FinlayL
  • 196
  • 8
Goblin
  • 43
  • 2
  • 3
  • 8
  • Tried- with open('x.csv','rb') as f1, open('y.csv','rb') as f2: – Goblin Aug 26 '14 at 08:02
  • Completely new to this! – Goblin Aug 26 '14 at 08:02
  • Is your problem to open the files or finding the difference between the two files? Please update your question and be specific. You have a higher chance of getting a useful answer if you ask one specific question only and provide details on how far you have got. – kkuilla Aug 26 '14 at 08:08
  • @spammer Have a read of the csv module https://docs.python.org/3.3/library/csv.html and give it another go. If you still have problems post your code and the error and someone will give you a hnad – FinlayL Aug 26 '14 at 08:09
  • Finding the difference of the two files is my problem. – Goblin Aug 26 '14 at 08:10
  • I have tried the same code as in http://stackoverflow.com/questions/11108667/comparing-two-csv-files-and-getting-difference and I am getting an empty set. – Goblin Aug 26 '14 at 08:24
  • I'm unable to code the logic and I'm new to the csv and python. Pls help somebody – Goblin Aug 26 '14 at 08:37
  • @spammer What output would you expect? A list returned, a separate csv, printed to console etc – FinlayL Aug 26 '14 at 09:37
  • @FinlayL: A separate csv please.. – Goblin Aug 26 '14 at 09:59

1 Answers1

0

From what I understand from the question, this should compare the files and create a third csv with the differences for each cell. Personally I don't think this is a very elegant solution and will break down in a range of scenarios but it should at least get you started. This was partially based off the linked Q/A given in the comments.

import csv


def csv_get(csvfile):
    with open(csvfile) as f:
        for row in csv.reader(f):
            for i in row:
                yield i


def csv_cmp(csvfile1, csvfile2, output):
    row = []
    read_file_2 = csv_get(csvfile2)

    for value_1 in csv_get(csvfile1):
        value_2 = read_file_2.next()
        print("File 1: {} File 2: {}").format(value_1, value_2)
        difference = int(value_1) - int(value_2)
        row.append(difference)

    with open(output, "w") as output_file:
        csv.writer(output_file).writerow(row)

    read_file_2.close()

csv_cmp(csvfile1="C:\\...\\a.csv",
        csvfile2="C:\\...\\b.csv",
        output="C:\\...\\c.csv")
FinlayL
  • 196
  • 8