I cannot get the expected results when modifying values in a txt.file

Question:

Hi guys I’m trying to modify some values in a file by the numbers I want.
The thing is that a rare value is being inserted in the last value added.
I have debugged but I still don’t understand how to fix it.
I have a file with numbers from 1 to 10 I want to change them by other numbers that I pass by function that increases by +1.

import re
import glob
import os

filename="myfile.txt"
                    
num = 9
def number():
    global num
    num += 1
    return str(num)

with open(filename, "r") as f:
    contents = f.read()
            
    #1 to 10        
    contents = re.sub(r'^1', str(number()), contents, flags = re.MULTILINE)
    contents = re.sub(r'^2', str(number()), contents, flags = re.MULTILINE)
    contents = re.sub(r'^3', str(number()), contents, flags = re.MULTILINE)
    contents = re.sub(r'^4', str(number()), contents, flags = re.MULTILINE)
    contents = re.sub(r'^5', str(number()), contents, flags = re.MULTILINE)
    contents = re.sub(r'^6', str(number()), contents, flags = re.MULTILINE)
    contents = re.sub(r'^7', str(number()), contents, flags = re.MULTILINE)
    contents = re.sub(r'^8', str(number()), contents, flags = re.MULTILINE)
    contents = re.sub(r'^9', str(number()), contents, flags = re.MULTILINE)
    contents = re.sub(r'^10', str(number()), contents, flags = re.MULTILINE)

with open(filename, "w") as f:
    f.write(contents)

myfile.txt these are the numbers it contains

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10

myfile.txt the numbers I expect

 10
 11
 12
 13
 14
 15
 16
 17
 18
 19

myfile.txt the numbers I get

 19
 11
 12
 13
 14
 15
 16
 17
 18
 190
Asked By: Maiinjoon

||

Answers:

The following describes your desired result in a simple numeric solution:

filename = "myfile.txt"

NUMBER = 9

with open(filename, "r") as f:
    content = f.readlines()
    new_string = "n".join([str(int(val) + NUMBER) for val in content])

with open(filename, "w") as f:
    f.write(new_string)

If your Problem is numerical solvable and you know that you should give it a try. It would be mostly faster than string shenanigans and in this case it is also easier to understand.

Answered By: MaKaNu

It appears that you want to add 9 to every integer value found on each line and modify the file accordingly.

If that’s the case then the re approach is probably not best suited to this problem.

How about:

filename = "myfile.txt"

ADD = lambda x: str(int(x) + 9)

with open(filename, "r+") as data:
    nums = data.readlines()
    data.seek(0)
    print(*map(ADD, nums), sep="n", file=data)
    # truncate is only really necessary if any of the source values are negative
    # it's benign otherwise
    data.truncate() 
Answered By: CtrlZ

Here is another solution using strings. We can use the pythonic way of getting the next line using for in file_object and re.sub our number() value with the digits on that line.

This allows our myfile.txt to be of the following format

1. test
2. test 2
3. test 4

and be output as

10. test
11. test 2
12. test 4

Of course the other text is purely optional so your original output will still match as well.

import re
import glob
import os

filename = "myfile.txt"

num = 9


def number():
    global num
    num += 1
    return str(num)


contents = ""
with open(filename, "r") as f:
    for contents_line in f:
        if re.match('^d+', contents_line):
            contents_line = re.sub('^d+', number(), contents_line)
        contents += contents_line
with open(filename, "w") as f:
    f.write(contents)
Answered By: Ted Possible
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.