Reputation: 3803
I have to replace several words in a txt file. I have a dict constructed where all the keys that occur in the file should be replace with its value.
f1 = open('testlist01.txt', 'r')
f2 = open('new_testlist.txt', 'w')
for line1 in f1:
for key1,value1 in new_class_names.iteritems():
str(line1).replace(key1, str(value1))
f2.write(line1)
print line1
f1.close()
f2.close()
f1 contains
Archery/v_Archery_g09_c06.avi 3
BandMarching/v_BandMarching_g10_c06.avi 6
BasketballDunk/v_BasketballDunk_g19_c01.avi 9
f2 should be changed to
5/10 3
20/954 6
62/548 9
Where new_class_names is a dict for eg:-
{'Archery':5, 'BandMarching':20, 'BasketballDunk':62, 'v_Archery_g09_c06.avi':10 ,
'v_BandMarching_g10_c06.avi':954, 'v_BasketballDunk_g19_c01.avi':548}
The code I tried does not replace it.
Upvotes: 0
Views: 460
Reputation: 321
Strings in python are immutable. str(line1).replace(key1, str(value1))
creates new string instance that gets lost. Assign the result to line1
and it will do the job.
str(line1).replace(key1, str(value1))
should become line1 = line1.replace(key1, str(value1))
Upvotes: 1