I have a Python file file1.py with the following code lines:
uname="[email protected]"
pwd="abcdef"
I want to replace and change the uname to "auto2mailnesia.com", then to "[email protected]" and so on and then use the updated uname in another file.
Consider a scenario where I want to update uname from auto1 to auto3.
I have another Python file file2.py with the below code lines:
from xxx.xxx import file1
for i in range(0,1):
currentuser = (uname[uname.index('auto') + 4:uname.index('@')])
newuser = str(int(currentuser) + 1)
newusername = uname.replace(currentuser, newuser)
print(uname)
print(currentuser)
print(newusername)
print(newuser)
with open(testdataFileName, 'r+') as f:
text = f.read()
text = re.sub(uname, newusername, text)
f.seek(0)
f.write(text)
When I run file2.py in a loop of 1, then the uname gets correctly updated in file1.py
Output is as follows:
[email protected]
1
[email protected]
2
But, when I run file2.py in a loop of say 3 then the uname gets updated in file1.py only once.
Output is as follows:
[email protected]
1
[email protected]
2
[email protected]
1
[email protected]
2
[email protected]
1
[email protected]
2
I do not understand why uname is being updated only once in file1.py while running in a loop.
Can someone please give an explanation for this?
Also, if someone could tell me what I am doing wrong and how to fix this it would be very much appreciated.
print? Now, look at the code. Why should those values get updated by the file contents? You changed the contents of the file, but why should that matter?file1.pywhereuname="[email protected]"touname="[email protected]". If you run it multiple times, I assume you want it to create new sets of uname & pwd pairs where the username keeps incrementing from 1 to 2 to 3 to 4 to .... as many times you run. Is my understanding correct?text. What happens the next time through theforloop? The first thing that happens iscurrentuser = (uname[uname.index('auto') + 4:uname.index('@')]). Butunamehas the same value now that it did before, thereforecurrentuserwill get the same value that it did last time, and so on. When you open the file this time around you will read the text again, but then attempt to replace the sameunamewith the samenewusername. This is why theunameonly gets updated once, as you complained: because nothing in the loop changes the value ofuname.