python - Matching parts of two csv files to return certain elements -
hello looking index match in excel new python data sets far large excel now
i dumb question right down as possible cause data contains alot of irrelevant information problem
csv (has 3 basic columns)
name, date, value
csv b (has 2 columns)
value, score
csv c (i want create using python; 2 columns)
name, score
all want enter date , have rows in csv match "date" , "score" associated "value" row in csv in csv b , returning in csv c along name of person. rinse , repeat through every row
any appreciated don't seem getting far
here working script using python's csv module:
it prompts user input date (format m-d-yy
), reads csva
row row check if date in each row matches inputted date.
if yes, checks if value corresponds date current row of matches of rows in csvb
.
if there matches, write name csva
, score csvb
csvc
.
import csv date = input('enter date: ').strip() = csv.reader( open('csva.csv', newline=''), delimiter=',') matches = 0 # reads each row of csva row_of_a in a: # removes whitespace before , after of each string in each row of csva row_of_a = [string.strip() string in row_of_a] # if date of row in csva has equal value inputted date if row_of_a[1] == date: b = csv.reader( open('csvb.csv', newline=''), delimiter=',') # reads each row of csvb row_of_b in b: # removes whitespace before , after of each string in each row of csvb row_of_b = [string.strip() string in row_of_b] # if value of row in csva equal value of row in csvb if row_of_a[2] == row_of_b[0]: # if csvc.csv not exist try: open('csvc.csv', 'r') except: c = open('csvc.csv', 'a') print('name,', 'score', file=c) c = open('csvc.csv', 'a') # writes name csva , value csvb csvc print(row_of_a[0] + ', ' + row_of_b[1], file=c) m = 'matches' if matches > 1 else 'match' print('found', matches, m)
sample csv files:
csva.csv
name, date, value john, 2-6-15, 10 ray, 3-5-14, 25 khay, 4-4-12, 30 jake, 2-6-15, 100
csvb.csv
value, score 10, 500 25, 200 30, 300 100, 250
sample run:
>>> enter date: 2-6-15 found 2 matches
csvc.csv (generated script)
name, score john, 500 jake, 250
Comments
Post a Comment