First, to have your replacement in the file, you need to actually write the result back to the file.
To do this, you have two options (cmp. Replace and overwrite instead of appending):
- Just open the file again in
w
mode after reading it and write the output of your replacement to it:
import tkinter as tk
import re
master = tk.Tk()
from tkinter.filedialog import askopenfilename
filename = askopenfilename()
pattern = '"name":"(.*?)"'
with open(filename, "r") as infile:
filetext = infile.read()
infile.close()
with open(filename, "w") as outfile:
outfile.write(re.sub(pattern, "test", filetext))
outfile.close()
- Use
seek
to move the beginning of the file and truncate
to inplace replace:
import tkinter as tk
import re
master = tk.Tk()
from tkinter.filedialog import askopenfilename
filename = askopenfilename()
pattern = '"name":"(.*?)"'
with open(filename, "r+") as infile:
filetext = infile.read()
infile.seek(0)
infile.write(re.sub(pattern, "test", filetext))
infile.truncate()
infile.close()
Second, concerning the main part of your question, the replacement by an incrementing number: I don't think you can do this with a single call of re.sub()
.
What you could do is read the file line by line and linewise substitute a counter variable. Whenever you successfully match, you increment your counter afterwards. To determine this, you could e.g. use re.subn()
which will not only return the new string but also the number of substitutions.
Full example:
import tkinter as tk
import re
master = tk.Tk()
from tkinter.filedialog import askopenfilename
filename = askopenfilename()
pattern = '"name":"(.*?)"'
with open(filename, "r") as infile:
filetext = ""
count = 1
line = infile.readline()
while line:
matchtuple = re.subn(pattern, str(count), line)
if matchtuple[1]:
count += 1
filetext += matchtuple[0]
line = infile.readline()
infile.close()
with open(filename, "w") as outfile:
outfile.write(filetext)
outfile.close()
Input:
"bla":"bal"
"name":"baba"
"blah":"blah"
"name":"keke"
Output:
"bla":"bal"
1
"blah":"blah"
2