Home > Back-end >  how to modify/add character of txt file based on identifier character in each line using python?
how to modify/add character of txt file based on identifier character in each line using python?

Time:11-08

I have a txt file and I want to add or change its contents based on the characters on each line,

let's say i wanted to add string "--" on each line but break the iteration when found string "*******" and continue add string "--" after found "#######"

Input file

aaaaaaa
bbbbbbb
*******
1234567
7654321
#######
ddddddd
eeeeeee

Desired Output

-- aaaaaaa
-- bbbbbbb
*******
1234567
7654321
#######
-- ddddddd
-- eeeeeee

My Code

file_name = 'abc.txt'
for line in fileinput.FileInput(file_name,inplace=1):
    line = line.replace(line,'--'   line)
    if '*******' in line:
        break
        print(line)
    elif '#######' in line:
        continue
        print(line)

But Give me this Result

-- aaaaaaa
-- bbbbbbb
-- *******

CodePudding user response:

This is just an idea; maybe this can help you :)

import sys
import os

fin = os.path.join(sys.path[0], 'abc.txt')
fout = os.path.join(sys.path[0], 'abc2.txt')

L = []
with open(fin, "r") as f:
    L = f.readlines()

flag = True
for i, line in enumerate(L):
    if (line.startswith("*")):
        flag = False
    elif (line.startswith("#")):
        flag = True
    elif (flag):
        L[i] = "-- "   L[i]

with open(fout, "w") as f:
    for line in L:
        f.write(line)

Output:

-- aaaaaaa
-- bbbbbbb
*******
1234567
7654321
#######
-- ddddddd
-- eeeeeee

CodePudding user response:

The below solution reads each line and checks if the line doesn't start with '*' or '#' and replace that line with the new line containing the suffix '---'

with open("test.txt", 'r') as fd:
    lines = fd.readlines()    
    for line in lines:
        line = line.strip('\n')
        if not (line.startswith("*") or line.startswith("#")):            
            line = line.replace(line, f'---{line}')
        print(line)

Output:

---aaaaaaa
---bbbbbbb
*******
---1234567
---7654321
#######
---ddddddd
---eeeeeee
  • Related