0

I am writing program in python. I want to save the updated file to keep the version change. How to append the lines at the beginning of the file. I tried seek(0,0) but its not working

Is there any thing I need to modify the Code

firfox.txt

 firefox-x 46.0:
 google 5.1.0.1:
     - request

file.py

 import re
 rx = r'\d+(?=:$)'
 with open('firfox.txt', 'r') as fr:
     data = fr.read()
     fr.seek(0,0)
     with open('firfox.txt', 'a') as fw:
         fw.seek(0,0)
         fw.write('\n')
         fw.write(re.sub(rx , lambda x: str(int(x.group(0)) + 1), data, 1, re.M))

I have written other file.py

import re
rx = r'\d+(?=:$)'
with open('firfox.txt', 'r+') as fr:
    data = fr.read()
    fr.seek(0,0)
    fr.write(re.sub(rx , lambda x: str(int(x.group(0)) + 1), data, 1, re.M))
    fr.write(data)

Here multiple lines are repeating like if i am executing twice firefox-x 46.0: line is coming twice

New Expected firfox.txt shown below. one time executing

 firefox-x 46.1:
 google 5.1.0.1:
     - request
 firefox-x 46.0:
 google 5.1.0.1:
     - request

If executing again python file expected out is below.

 firefox-x 46.2:
 google 5.1.0.1:
     - request
 firefox-x 46.1:
 google 5.1.0.1:
     - request
 firefox-x 46.0:
  google 5.1.0.1:
     - request

1 Answers1

0

Try this:

 import re
 rx = r'\d+(?=:$)'
 with open('firfox.txt', 'r') as fr:
     data = fr.read()
     fr.close()
     with open('firfox.txt', 'w') as fw: # w mode always start from beginning 
         fw.write(re.sub(rx , lambda x: str(int(x.group(0)) + 1), data, 1, re.M))   
         fw.write('\n')
         fw.write(data) 
         fw.close()

Just write previous text file data after writing your new data

Narendra Lucky
  • 340
  • 2
  • 13
  • if i am executing 2 times then out is not proper firefox-x 46.2: google 5.1.0.1: - request firefox-x 46.1: google 5.1.0.1: - request firefox-x 46.0: google 5.1.0.1: - request firefox-x 46.0: google 5.1.0.1: - request firefox-x 46.1: google 5.1.0.1: - request –  Jun 26 '19 at 11:23