0

I have a file with strings like this:

Text_0_0
Text_0_1
...
Text_0_19
Text_1_0
...
Text_39_19

I want to replace it with values that has to be calculated out of the numeric values:

Text_x_yText_z

Where z = x * 20 + y.

So after the operation the file should look like this:

Text_0
Text_1
...
Text_19
Text_20
...
Text_399

With the following code I can find the numeric values and calculate the correct number:

import re
import sys
f = open("file.txt", "r")
f.seek(0)
for line in f:
    data = re.findall("Text_(\d*)_(\d*)", line)
    if data is not None:
        if len(data) == 1:
            if len(data[0]) == 2:
                number= int(data[0][0])  * 20 + (int(data[0][1]) + 1)
                print (number)
f.close()

But how to write the correct values into the file?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Instead of `print`, write to the new file? (That you've opened before with `open(..., 'w')`) – mkrieger1 Feb 27 '20 at 10:47
  • Also, see [Use Regular expression with fileinput](https://stackoverflow.com/questions/3043849/use-regular-expression-with-fileinput) – Wiktor Stribiżew Feb 27 '20 at 10:50
  • @mkrieger1 The `print`command was only to test the output. The code only prints the calculated values but not the whole text. In the file is a lot of other stuff which should be untouched. So my question is not really answerded... – Oliver Wieland Feb 27 '20 at 11:06
  • Then I'm not sure I understand what the question is. Why not simply write the untouched stuff to the other file, too? – mkrieger1 Feb 27 '20 at 12:35
  • You are right. I thought too complicated... Thanks. – Oliver Wieland Feb 27 '20 at 14:07

0 Answers0