Write to file by increment the number

I have a file and need to increment the digit in the file and save to another file, and it will keep on increment. The code I have written is absolutely working except for one condition. The file2 has to increase by one and keeps adding one if the last digit exist in the file2

Last digit of file2 (output) increments only one time but need to increment infinite till execution stop

After the 3rd execution still output 5.1:1 rather than 5.1:2 Alternate way also appreciated

import re
import os
rx = r'(?<=:)(\d*)

rex = r'(?<=:)(\d+)

with open('file1','r') as fh:
    fh_n = fh.read()
    with open('file2', 'a+') as fw:
        x = re.sub(rx , lambda x: str(int(x.group(0)) + 1) if len(x.group(1)) else "0", fh_n, 1, re.M)
        fw.seek(0, os.SEEK_SET) 
        if x in fw.read():
           y = re.sub(rex , lambda x: str(int(x.group(0)) + 1) , x, 1, re.M)
           fw.seek(0, os.SEEK_END)  


    firefox 5.1:
          chrome 5.0:

file2 ( Expected output is below )

After 3 times execution

    firefox 5.1:0
          chrome 5.0:
    firefox 5.1:1
          chrome 5.0:
    firefox 5.1:2
          chrome 5.0:

Well if your code is as you’ve pasted it, the problem should be fairly clear from the syntax highlighting that the forum has applied to your patterns…

And your code works exactly as expected from my end.

file2 will contain:

    firefox 5.1:0
          chrome 5.0:    firefox 5.1:1
          chrome 5.0:    firefox 5.1:1
          chrome 5.0:

with the code you have written.

Consider this: the contents of file1 never change, so the value of x never changes. What are you telling y to be?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.