Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading