私は3つのファイルを持っています。果物が含まれる列と一致する列を比較したいのですが、一致する果物を 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、行2 行 2 など>)。メイン スクリプトを実行した後、テスト ファイルは、レコードなしまたは最大 5 つのレコードで設定できます。追加ファイルは空にすることも、何百ものレコードを含めることもできます。Python 2.7 を使用しています。
また、完了時にファイルを昇順でソートする方法についてもわかりません。