Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine multiple lines of text into one line in Python with a delimiter to separate them?

Tags:

python

text

I have the following in a text file:

line1
text1
text2
text3
line2
something1
something2

I want to create another text file that looks like this:

line1|text1|text2|text3
line2|something1|something2

Whenever a line in the text file says "line" I want to add each line below it to that line with a '|' delimiter. Can I do this in Python?

like image 734
coderman Avatar asked Apr 26 '11 14:04

coderman


People also ask

How do I combine multiple lines in one line?

When you want to merge two lines into one, position the cursor anywhere on the first line, and press J to join the two lines. J joins the line the cursor is on with the line below. Repeat the last command ( J ) with the . to join the next line with the current line.


1 Answers

If your file is not EXTREMELY big

data=open("file").readlines()
for n,line in enumerate(data):
    if line.startswith("line"):
       data[n] = "\n"+line.rstrip()
    else:
       data[n]=line.rstrip()
print '|'.join(data)
like image 125
ghostdog74 Avatar answered Oct 15 '22 14:10

ghostdog74