I have three files. I want to compare columns with fruit in them and those that match, I want to append the matching fruit to the Append.txt file and then sort ascending.
test1.csv
CustID,Name,Count,Item,Date
23,Smith,8,apples,08/12/2010
1,Jones,8,banana,03/26/2009
15,Miller,2,cookie dough,03/27/2009
6,Fisher,8,oranges,06/09/2011
test2.csv
FRUIT,Amount,Aisle
oranges,1,1
apples,1,1
pears,1,1
Append.txt
Fruit,Total,Aisle
cherries,1,1
dates,2,1
grapes,5,1
kiwis,2,2
peaches,2,2
plums,1,1
watermelon1,2
Code:
import csv
# Iterate through both reader1 and reader2, compare common row, and append matching column data to test.txt in its matching column
with open("C:\\Test\\Append.txt", 'a') as f:
reader1 = csv.reader(open("C:\\Test\\test1.csv", 'rb'), delimiter=',')
row1 = reader1.next()
reader2 = csv.reader(open("C:\\Test\\test2.csv", 'rb'), delimiter=',')
row2 = reader2.next()
if (row1[3] == row2[0]):
print "code to append data from row1[0] to test.txt row[0] goes here"
f.close()
exit
print "code to sort test.txt ascending on column[0] goes here"
My initial script will not work. After examining I can see that the code only compares row 1 with row 1, row 2 with 2, etc. and I really want it to compare all rows (row1 with row 1, row1 with row 2, row 2 with row 1, row 2 with row 2, etc>). After running main script, test files can be populated with no records or up to 5 records. Append file can be either empty or have hundreds of records. Using python 2.7.
I am also unsure as to how to sort the file in ascending order when done.