I am in the process of learning Python.
I already know R but I will admit I am struggling to learn Python.
I am using the code found here
This is the code:
checkWords = ("old_text1","old_text2","old_text3","old_text4")
repWords = ("new_text1","new_text2","new_text3","new_text4")
for line in f1:
for check, rep in zip(checkWords, repWords):
line = line.replace(check, rep)
f2.write(line)
f1.close()
f2.close()
The input looks like the following:
This is old_text1.
This is old_text2.
This is old_text3.
This is old_text4.
The above code works fine and I get the expected output.
However, if I try to put the above into a function, like this...
def test(f1, f2):
checkWords = ("old_text1","old_text2","old_text3","old_text4")
repWords = ("new_text1","new_text2","new_text3","new_text4")
for line in f1:
for check, rep in zip(checkWords, repWords):
line = line.replace(check, rep)
f2.write(line)
f1.close()
f2.close()
file1 = open('test_file1.txt', 'r')
file2 = open('test_file2.txt', 'w')
test(file1, file2)
The output looks like the following:
This is new_text1.
This is new_text1.
This is new_text1.
This is new_text1.
This is old_text2.
This is new_text2.
This is new_text2.
This is new_text2.
This is old_text3.
This is old_text3.
This is new_text3.
This is new_text3.
This is old_text4.
This is old_text4.
This is old_text4.
This is new_text4.
Somewhere it looks as if it is looping through the function but I don't see how. In addition, it looks as if when it loops through the 2nd - 4th time, the output is not correct.
I tried taking checkWords and repWords outside of the function but that did not help.
Can someone please explain to me why this is happening and how can it be fixed?
Thanks in advance.
Dan