2013-03-28 3 views
0

세 개의 파일이 있습니다. 열과 과일을 비교하고 싶습니다. 일치하는 열매를 Append.txt 파일에 추가 한 다음 오름차순으로 정렬하고 싶습니다.두 CSV 파일의 값 비교, 텍스트 파일에 값 추가

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, 행 1, 행 2, 행 3, 2 행 2 등>). 주 스크립트를 실행 한 후 테스트 파일에는 레코드가 없거나 최대 5 개의 레코드가 채워질 수 있습니다. 추가 파일은 비어 있거나 수백 개의 레코드가있을 수 있습니다. 파이썬 사용하기 2.7.

완료되면 오름차순으로 파일을 정렬하는 방법을 잘 모르겠습니다.

답변

1

sets을 사용하십시오. 먼저 두 개의 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))) 
+0

전체적으로 작동했습니다. 나는 | 12 행에서 'w'를 'a'로 변경합니다. 그렇지 않으면 Append.txt 파일의 기존 데이터를 덮어 씁니다. 어쨌든 Append 파일의 끝 부분에 개행 문자를 넣으시겠습니까? 저 같은 초보자들도 CSV를 가져 오는 것을 잊지 마십시오. 야후. 감사. – user12059

+0

@ user12059 : 맞습니다. 저는 귀하의 질문을 약간 다르게 해석했습니다. '|'을 제거하면'Append.txt'에 열거 된 과일 *에 대해서는 신경 쓰지 않아서 그 파일을 모두 읽지 않게되었습니다. 추가 줄 바꿈을 추가했습니다. –

+0

완벽. 이제는 마지막 대괄호 안에 중첩 될 것입니다. 너의 새로운 BFF. :-) – user12059