简体   繁体   中英

How do i combine 2 lines in a text file in python?

I need help combining 2 lines together in a text file, so for example: My text file looks something like this:

Line 1

Line 2

Line 3

I want to combine Line 2 into line 1 then print the content of the text file so it looks something like this:

Line 1 Line 2

Line 3

I know how to print the content of the file using: Print file.read()

I just don't understand how to combine the first 2 lines.

The other posts fail to show you how to combine only the first and second lines before printing the rest of the file. You may or may not desire a space inbetween the lines as I have done. Here is an example:

with open('file.txt') as f:
    line1 = f.readline().strip()
    line2 = f.readline().strip()
    print line1 + " " + line2
    for other_line in f:
        print other_line.strip()

You file is stored with strings having '\\n' in-between every sentence.

To combine lines, Open your file. Read the contents and split the lines to form a list of strings. Now join them with ' '(space).

with open('sample.txt') as f:
    print(" ".join(f.read().splitlines()))

For combining every two lines,

>>> with open('sample_log.txt') as f:
...     content = f.read().splitlines()                                         ... 
>>> 
>>> print "\n".join(" ".join(two_lines) for two_lines in zip(content[::2],content[1::2]))+(content[-1] if len(content)%2!=0 else '')

Here, for example, if

>>> content = ['a','b','c','d','e','f','g']                                     >>> zip(content[::2],content[1::2])
[('a', 'b'), ('c', 'd'), ('e', 'f')]
>>> [' '.join(twos) for twos in zip(content[::2],content[1::2])]
['a b', 'c d', 'e f']
>>> "\n".join(' '.join(twos) for twos in zip(content[::2],content[1::2]))
'a b\nc d\ne f'
>>> print "\n".join(' '.join(twos) for twos in zip(content[::2],content[1::2]))
a b
c d
e f
>>> print "\n".join(' '.join(twos) for twos in zip(content[::2],content[1::2])) + ("\n"+content[-1] if len(content)%2!=0 else '')
a b
c d
e f
g
>>> 

If you want to combine only the first two lines then,

number_of_lines_to_combines=2
content=[]
with open('sample_log.txt') as f:
    for line in f.readlines():
        if number_of_lines_to_combines>0:
            number_of_lines_to_combines-=1
            content.append(line.rstrip()) #rstrip is used to get rid of new line
        else:
            content.append(line) # append with new line
print "".join(l)

You can try this:

l1, l2, l3 = [i.strip('\n') for i in open('filename.txt')]
new_lines = ["{} {}".format(l1, l2), l3]
print('\n'.join(new_lines))

This should work

with open('lines.txt') as f:
    all_lines = f.readlines()
    all_lines = [x.strip() for x in all_lines if x.strip()]
    two_lines = " ".join(x for x in all_lines[:2])
    lines_left = " ".join(x for x in all_lines[2:])

    print two_lines
    print lines_left

Output

Line 1 Line 2

Line 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM