0

私は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 を使用しています。

また、完了時にファイルを昇順でソートする方法についてもわかりません。

4

1 に答える 1

1

セットを使用します。最初に 2 つの CSV ファイルを読み取り、行から果物だけを収集します。

次に、集合交差を使用して、2 つのファイルに共通するすべての果物を見つけ、これらを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)))
于 2013-03-28T20:42:39.113 に答える