Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

How to insert a newline with amended text in Python if conditions are met?

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

  • 12512512
  • TitleZ

#and so on

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use inside the string. This should produce a new line.

I believe this should help:

https://www.freecodecamp.org/news/python-new-line-and-how-to-python-print-without-a-newline/

https://www.pitt.edu/~naraehan/python2/tutorial7.html#:~:text=In%20Python%20strings%2C%20the%20backslash,r%22%20is%20a%20carriage%20return.&text=Conversely%2C%20prefixing%20a%20special%20character,it%20into%20an%20ordinary%20character.

I also created some indentation. Let me know if this helps!

if "1 1 1 1" in line:
    line.replace("1 1 1 1", "
Title2")
    print(line)
    #This will add a new line with Title2 in the string

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) 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...