Reputation: 79
I have two csv files in the following format:
First file (data.csv):-
1,red 3,blue 4,green 2,gray 5,black
Second file (text.csv):-
1 3 2 4
My goal is to read second file (text.csv) and store the numbers probably in a list. Then I want to locate the colors that correspond to these numbers in first file (data.csv).
Hence, my final output should look something like:
1,red 2,gray 3,blue 4,green
I want to consider the use of dictionary but can't seem to understand how I will do it.
Upvotes: 1
Views: 367
Reputation: 2768
This should work:
D = {}
with open('data.cvs') as f:
for line in f:
x, y = line.split(',')
D[int(x)] = y
print D[1]
Upvotes: 0
Reputation: 56654
Using the csv
module can save you some headaches; try
import csv
import sys
# version compatibility shim!
if sys.hexversion < 0x3000000:
# Python 2.x
opencsv = lambda f: open(f, mode="rb")
else:
# Python 3.x
opencsv = lambda f: open(f, newline="")
# read color data to a dictionary
with opencsv("data.csv") as inf:
color = {int(num):col for num,col in csv.reader(inf)}
# do translation
with opencsv("text.csv") as inf:
for num, in csv.reader(inf):
num = int(num)
print("{},{}".format(num, color[num]))
which produces
1,red
3,blue
2,gray
4,green
(same order as text.csv file)
Upvotes: 4
Reputation: 11943
#First populate the data dictionnary with data.csv file :
data = {}
with open('data.csv', 'r') as f:
for line in f:
try:
index, value = line.split(',')
data[index.replace('\r','').strip()] = value.replace('\r','').strip()
except Exception as e:
print('[!] Error hanling data line : %s - %s' % (line, e))
#Then compare the second file :
with open('text.csv', 'r') as f:
for line in f:
try :
line = line.replace('\r','').strip()
print('%s => %s' % (line, data[line]))
except Exception as e:
print('[!] Error finding %s in data - %s' % (line, e))
Upvotes: 1