Duplicate a line in TXT file and increase number inside it every time it duplicates

74 views Asked by At

Let's say I have this line in TXT file:

ABCD1EFGH

What I want to do is repeat the line for an amount number of times but the number 1 will increase by 1 every time it duplicates. like that:

ABCD1EFGH
ABCD2EFGH
ABCD3EFGH
ABCD4EFGH

What is the code for Python to do so?

I haven't tried any method yet, I have no clue.

5

There are 5 answers

1
Elerium115 On

I'll let the part of reading from a file and writing back to it as an exercise for you.

Also according to your example I assume the number is prefixed and suffixed by exactly 4 characters

txt = "ABCD1EFGH"
number = int(txt[4])
for i in range(12):
    print(f"{txt[:4]}{number + i}{txt[5:]}")

ABCD1EFGH
ABCD2EFGH
ABCD3EFGH
ABCD4EFGH
ABCD5EFGH
ABCD6EFGH
ABCD7EFGH
ABCD8EFGH
ABCD9EFGH
ABCD10EFGH
ABCD11EFGH
ABCD12EFGH
1
Edo Akse On

In case the input string is of indeterminate length, with the following structure LETTERS then NUMBER(S) then LETTERS again, the following function would do what you want. Note that you can use REGEX as well, and the function can be simplified quite a bit. I'm opting for the longer version so you can see what is being done.

def inc_number(astring: str) -> str:
    start = None
    end = None
    for i, c in enumerate(astring):
        if c.isnumeric():
            start = i
            break
    for i, c in enumerate(astring[start:]):
        if not c.isnumeric():
            end = i+start
            break
    start_string = astring[:start]
    number = int(astring[start:end])+1
    end_string = astring[end:]
    result = f"{start_string}{number}{end_string}"
    return result
    

astring = "ABCD1EFGH"
for i in range(5):
    astring = inc_number(astring)
    print(astring)

astring = "thisistext41thisismoretext"
for i in range(5):
    astring = inc_number(astring)
    print(astring)

Output:

ABCD2EFGH
ABCD3EFGH
ABCD4EFGH
ABCD5EFGH
ABCD6EFGH
thisistext42thisismoretext
thisistext43thisismoretext
thisistext44thisismoretext
thisistext45thisismoretext
thisistext46thisismoretext
0
Mahboob Nur On

Try like this

def duplicate_and_increase_number(line, amount):
    result = []
    for i in range(1, amount + 1):
        new_line = line.replace('1', str(i), 1)
        result.append(new_line)
    return result

content = 'ABCD1EFGH'
duplicates = duplicate_and_increase_number(content, 4)  # Change 4 to the desired amount
for text in duplicates:
    print(text)

Output:

ABCD1EFGH
ABCD2EFGH
ABCD3EFGH
ABCD4EFGH
1
SVBazuev On

INPUT file.txt:

ABCD1EFGH
EFGH33ABCD

CODE:

import re

# Specify how many modified rows you want to get
ITER = 4


with open("test.txt", "r+", encoding="utf-8") as f:
    promo_codes = f.readlines()

    for p_c in promo_codes:
        num = int(re.search(r"(?![A-Z]{4})(\d{1,})", p_c).group(1))
        end_num = num + ITER
        l_chips = re.search(r"(^[A-Z]{4})", p_c).group(1)
        r_chips = re.search(r"\d([A-Z]{4}?)", p_c).group(1)

        while num < end_num:
            num += 1
            print(f"{l_chips}{num}{r_chips}", file=f)

OUTPUT file.txt:

ABCD1EFGH
EFGH33ABCD
ABCD2EFGH
ABCD3EFGH
ABCD4EFGH
ABCD5EFGH
EFGH34ABCD
EFGH35ABCD
EFGH36ABCD
EFGH37ABCD
0
sampriti On

You can try it this way too.The code is simply based on nested looping.

  1. Original content of file:
ABC12EFG
HIJ4KLM
  1. Input:
t=int(input("no.of loops="))
m=open("demofile3.txt","r")
a=m.readlines()
b=a
for i in range(0,t):
    a=b
    b=[]
    for j in a:
        print(j)
        p=""
        d=0
        f=0
        for k in range(0,len(j)):
            if j[k].isnumeric():
                    if j[k+1].isnumeric():
                      f=10*int(j[k])
                      d=d+f
                    else:
                      d=d+int(j[k])
                      p=p+str(d+1)
            else:
                p=p+j[k]
        b.append(p)
  1. Output(when loop is run 3 times):
ABC12EFG
HIJ4KLM
ABC13EFG
HIJ5KLM
ABC14EFG
HIJ6KLM

Hope it helped :)