Home > OS >  If a line starts with a string print THAT line and THE FOLLOWING one
If a line starts with a string print THAT line and THE FOLLOWING one

Time:02-07

this is my first post in the Stack Overflow community.Thanks in advance.

I have the following text structure

name:Light
component_id:12
-------------------
name:Normallight
component_id:13
-------------------
name:Externallight
component_id:14
-------------------
name:Justalight
component_id:15

I wonder how can I print the lines that start with "name" together with the next one that starts with "component_id" So that it looks something like this using Python:

name:Light,component_id:12
name:Normallight,component_id:13
name:Externallight,component_id:14
name:Justalight,component_id:15

So far I have this script but it only prints the lines that starts with "name"

x = open("file.txt")

for line in x:
    if line.startswith("name")
        print(line)

Thanks

CodePudding user response:

One approach would be to read the entire file into Python as a string, then use regular expressions:

import re
with open('file.txt', 'r') as file:
    lines = file.read()

matches = [x[0]   ','   x[1] for x in re.findall(r'\b(name:\w )\s (component_id:\d )', lines)]
print('\n'.join(matches))

This prints:

name:Light,component_id:12
name:Normallight,component_id:13
name:Externallight,component_id:14
name:Justalight,component_id:15

CodePudding user response:

How about using a variable?

x = open("file.txt")

found = None

for line in x:
    if line.startswith("name"):
        found = line
    elif found is not None:
        print(found   ","   line)
        found = None

CodePudding user response:

If your structure is just composed of three types of lines, and you know that the line that starts with component id comes after the line that starts with name, then you can try to store it in a variable when name appears and then print the entire line when the component id line comes up.

For example:

for line in x:
    if line.startswith("name"):
        temp = line
    if line.startswith("component_id"):
        print(temp   ','   line)
  •  Tags:  
  • Related