I'm using Python 3.6. I have a text file test.txt and I read it line by line.
In the text file, I have multiple entries of Titles like: TitleX, TitleY, TitleZ.
I want that IF a line contains 4 consecutive 1 1 1 1 on it to enter a new line below it (after the last 1 1 1 1 entry on each region (within a Title)) and write as a text "TitleX2", "TitleY2", "TitleZ2" and so on depending on the previous title to add 2 after it. So strings should be used.
This is what I have for the moment:
filepath = 'test.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
print("Line {}: {}".format(cnt,line.strip()))
line = fp.readline()
# if(line contains 1 1 1 1 and is the last of that type) then insert new line
#below it with string "Title2" depending on which
#regions the 1 1 1 1 belongs to (such as TitleX,TitleY, or TitleZ) as there are hundreds of those
#Titles in the text file.
cnt += 1
Text file is like this:
- TitleX
- 1234
- 51421
- 1231512
- 12521
- 1 1 1 1
- 1 1 1 1
- 1 1 1 1
#Should insert TitleX2 here
- 1151261
- TitleY
- 35126
- 124125
- 1 1 1 1
- 1 1 1 1
#Should insert TitleY2 here
#and so on
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…