Reputation: 125
I have the following reference data like
21 1
32 2
45 3
and there is a text file (file.txt) contains two or more columns like
21 32 45
45 21 32
32 45 21
I would like to change file.txt using reference value like
1 2 3
3 1 2
2 3 1
As you can see the reference file, 21, 32, and 45 equal and match the number 1, 2, and 3, respectively.
I coded based on two for loops and compared two values.
with open('ref') as f1, open('file.txt') as f2, open('out.txt', 'w') as f3:
for lines in f1:
value1 = lines.split()
for line in f2:
if value2 == value1[0]:
value2 = value1[1]
line = ' '.join(value2) + '\n'
f3.write(line)
Nothing has been changed. How could this make it possible?
Upvotes: 0
Views: 145
Reputation: 59260
You need a third loop to iterate over the columns of file.txt
. Something like
for line in f2:
value2 = line.split()
for item in value2:
if item == value1[0]:
value2 = value1[1]
A dict seems a good fit to your problem:
#/usr/bin/env python
ref = {}
with open("ref") as file:
for line in file:
k, v = line.split()
ref[k] = v
with open("file.txt") as file, open("res", 'w') as res:
for line in file:
for item in line.split():
res.write("%s\t" % ref[item])
res.write("\n")
Upvotes: 1
Reputation: 1457
mydict = {}
with open('ref') as f1:
for line in f1:
key, value = line.split()
mydict[key] = value
with open('file.txt') as f2, open('out.txt', 'w') as f3:
for l in f2:
line = l.split()
newline = ''
for item in line:
newline += mydict[item] + " "
f3.write(newline + "\n")
Upvotes: 1
Reputation: 1850
You are NOT comparing it right
with open('ref') as f1, open('file.txt') as f2, open('out.txt', 'w') as f3:
for lines in f1:
value1 = lines.split()
for line in f2:
value2 = line.split() # value2 is a list
if value2 == value1[0]: # if a list is equals to a value => always false
value2 = value1[1]
line = ' '.join(value2) + '\n'
f3.write(line) # so line is still the original line since the if statement is always false
Upvotes: 1