[英]Compare values from two csv files, append value to text file
我有三個文件。 我想比較其中有水果和匹配水果的列,我想將匹配水果附加到Append.txt文件中,然后升序排序。
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
碼:
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"
我的初始腳本不起作用。 檢查后,我看到代碼僅將第1行與第1行進行比較,將第2行與2作比較,依此類推,我真的希望它比較所有行(第1行與第1行,第1行與第2行,第2行與第1行,第1行) 2與第2行,等等>)。 運行主腳本后,可以填充無記錄或最多5條記錄的測試文件。 追加文件可以為空或具有數百條記錄。 使用python 2.7。
我也不確定如何在完成后按升序對文件進行排序。
使用集 。 首先閱讀兩個CSV文件,然后僅從行中收集水果。
然后使用集合交集找到兩個文件共有的所有水果,將它們添加到Append.txt
文件中的水果中,進行排序,然后將所有水果寫回到該文件中。
import csv
# collect the fruits of both CSV files
with open('c:/Test/test1.csv', 'rb') as test1:
reader = csv.reader(test1)
next(reader, None) # ignore header
test1_fruit = set(row[3] for row in reader)
with open('c:/Test/test2.csv', 'rb') as test2:
reader = csv.reader(test2)
next(reader, None) # ignore header
test2_fruit = set(row[0] for row in reader)
# Read all the fruit from Append
with open("C:/Test/Append.txt", 'r') as append:
fruit = set(line.strip() for line in append if line.strip())
# add all fruit that are in both test1 and test2
fruit |= test1_fruit & test2_fruit
# write out a sorted list
with open("C:/Test/Append.txt", 'w') as append:
append.write('\n'.join(sorted(fruit)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.