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