How to read multiple files from a folder and add new lines in the files based on the condition

Is there any easy method with python for reading and adding a new line for all the files in a folder when condition met.

I have 2 files ABC.TXT and DEF.TXT with the below content.

ABC.TXT

AAAAAA* TEST                                                           *
BBBBBB*=====================
CCC1QR     RAQWERT 
BBBBBB*=====================
RBBBBB =====================
MBBBBB =====================
DEF.TXT


RRR AA* TEST                                                           *
QWRRAB*=====================
CCC1QR     123QWE 
BBBBBB*=====================
JBBBBB =====================
RBBBBB =====================

When there is a space in the 7 th position of a line, I need add 2 lines(starting at position 8) and rewrite the files as is. The new lines to be added only once when it finds the space first time on the file at position 7. ABC.TXT

AAAAAA* TEST                                                           *
BBBBBB*=====================
CCC1QR     RAQWERT 
       here is my line1
       here is my line2
BBBBBB*=====================
RBBBBB =====================
MBBBBB =====================

DEF.TXT

RRR AA* TEST                                                           
QWRRAB*=====================
CCC1QR     123QWE 
       line1 added after first find of space
       line2 added after first find of space
BBBBBB*=====================
JBBBBB =====================
RBBBBB =====================

Thanks

Answer

This is the code. The comments along the way will explain the code

files = ["ABC.txt","DEF.txt"]
for file in files: #Looping through all the files
  f = open("ABC.txt", "r")
  para = f.read()
  spaceDetected = False #To ensure we add lines only one time
  newPara = ""
  for line in f.read():
    if line[6] == " " and spaceDetected == false: # Checking if the letter at index 6, which is the 7th letter is a space and the 2 lines have not been added yet
      newPara += line + "       This is my line 1n       This is my line 2n"#You may need to remove the newline from end and add one to the start
    else:
      newPara += line 
  w = file.open(file,"w")
  w.write(newPara)

This should sort through all the files and do what you want. Though this does look like you school project, I had some free time

Leave a Reply

Your email address will not be published. Required fields are marked *