Home > database >  split the text and make a list of list
split the text and make a list of list

Time:07-11

I have text file and I want to split the files and make it list where it is starting from @Given, @When and @And and put in a list, below files look like this

@Given
 User Username{
 User Userpassowrd 
 User ID 
 }
@When
User Username{
User Userpassowrd 
User ID 
}
@And
User Username{
User Userpassowrd 
User ID 
}

and i want to out put like this ,

Final_List=

      [@Given
      User Username{
      User Userpassowrd 
      User ID 
         }],
       [@When
        User Username{
        User Userpassowrd 
        User ID 
        }],
        [@And
         User Username{
         User Userpassowrd 
         User ID 
          }]
      

CodePudding user response:

You could use for loop to iterate over lines of txtFile by split('\n') with break line and startswith to check if it start with '@' ot with closing curly brace '}' store lines in list and finally join them back with new line '\n' and show them with print!

txtFile = """
@Given
 User Username{
 User Userpassowrd 
 User ID 
 }
@When
User Username{
User Userpassowrd 
User ID 
}
@And
User Username{
User Userpassowrd 
User ID 
}
"""
output = []
for line in txtFile.split('\n'):
    if(line.startswith("@")):
        output.append('[' line)
    elif(line.strip().startswith("}")):
        output.append(line "],")
    else:
        output.append(line)
print('\n'.join(output)[0:-2])

Result:

[@Given
 User Username{
 User Userpassowrd
 User ID
 }],
[@When
User Username{
User Userpassowrd
User ID
}],
[@And
User Username{
User Userpassowrd
User ID
}]
  • Related