简体   繁体   English

如何在Python的文本文件中合并2行?

[英]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 1号线

Line 2 2号线

Line 3 3号线

I want to combine Line 2 into line 1 then print the content of the text file so it looks something like this: 我想将第2行合并为第1行,然后打印文本文件的内容,因此它看起来像这样:

Line 1 Line 2 1号线2号线

Line 3 3号线

I know how to print the content of the file using: Print file.read() 我知道如何使用以下命令打印文件的内容: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. 您的文件存储的字符串中每个句子之间都有'\\ n'。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何按特定顺序组合文本文件中的行? - How do I combine lines in a text file in a specific order? 如何在文本文件中追加数据并使用 python 将多个文本文件合并为一个文本文件? - How do I append the data in text files and combine multiple text files into one text file using python? 如何从 python 脚本的文本文件中 select 某些行? - How do I select certain lines in a text file from python script? 如何使用 python 仅将 URL 中的特定文本行保存到 txt 文件? - How do I save only specific lines of text from a URL to a txt file using python? 如何使用sed -n在Python中从文本文件中提取一系列行? - How do I extract a range of lines from a text file using sed -n but in Python? 如何在 python 3.8 中的文本文件的所有行中循环“for”循环? - How do I make the “for” loop cycle through all lines of a text file in python 3.8? 如何在 Python3 中从没有格式字符(反斜杠/撇号)的文本文件中导入行 - How do I import lines from a text file without format characters (backslashes/apostrophes) in Python3 如何使用变量将文本行写入文件? - How do I write text lines to file with variables to a file? 如何在Python中使用分隔符将多行文本组合成一行来分隔它们? - How can I combine multiple lines of text into one line in Python with a delimiter to separate them? 如何使用 python 将文本行转换为 HTML 链接? - How do I convert lines of text into HTML links using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM