0

Hi,

I'm trying to create a piece of code which joins a line that matches a string, and the next succeeding line (no matter what this line contains). I'm getting confused at what Regular Expression (RE) to use.
So far I have:

input1 = open("out.txt","r")
output1 = open("outp.txt","w")

with input1 as f:
	out = ''.join(line for line in f
		if any(line.startswith(word) for word in ('a)','b)','c)','d)')))
with output1 as f:
	f.write(out)

output1.close()

So, I want to select a line that starts with a) and the next line (so in this example, 123):

a) Foo
123
b) Foobar
456

Any help would be greatly appreciated!
Thanks!!

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by joejoe92
0

You are not getting to out the lines that are after the tagged lines. Add to line the next one stripping the new line:

input1 = open("in.txt")
output1 = open("outp.txt","w")

with input1 as f:
	out = ''.join('%s %s' % (line.rstrip(),next(f)) for line in f
		if line.startswith(('a)','b)','c)','d)'))) # startswith works with tuple

#print out # debug
with output1 as f:
	f.write(out)
# no close!

Edited by pyTony: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.