如果它们以某些单词开头,如何将下一行打印到当前行?

时间:2019-05-27 14:22:47

标签: python

我要在当前行上打印下一行,条件是当前行以"This"开头,下一行以"That"开头,然后将其写回到同一文件中。我该如何实现?

注意:我的文件中还有其他几行需要保持不变。

prev = ''
with open("myfile.txt", 'r') as f:
    for line in f:
        if line.startswith('This') and prev.startswith('That'):
        # Attach 'That' line with 'This' line
        prev = line
#Once done, write back to myfile.txt

输入:

Foo
This is my current line
That is my next line
Bar

输出:

Foo
This is my current line That is my next line
Bar

3 个答案:

答案 0 :(得分:1)

您可能希望先在for循环之外将第一行和第二行存储到2个变量(prevcur)中,然后再检查第一行是否以“ This”开头和第二行以“那个”

编辑:我已经编辑了答案,以便可以在多行文件中使用。在多行的情况下,您可能希望将文件行存储在字符串lines的列表中,而不是使用1或2个变量。将文件内容存储到列表中之后,可以使用while循环遍历文件行。我使用while循环代替for,因为它在导航数组索引时为您提供了更大的自由度。

lines = []
with open("myfile.txt", 'r') as f:
    for line in f:
        lines.append(line.replace('\n', '').replace('\r', ''))

with open("myfile.txt", 'w') as f:
    length = len(lines)
    i = 0
    while i < length - 1:
        if lines[i].startswith('This') and lines[i + 1].startswith('That'):
            f.write(lines[i] + ' ' + lines[i + 1] + '\n')
            i += 1 # skip the next line because it is concated with the current line
        else:
            f.write(lines[i] + '\n')
        i += 1

    # when the last line doesn't concat with its previous line
    if i < length:
        f.write(lines[i] + '\n')

答案 1 :(得分:0)

我们希望将不以This开头的行直接附加到输出。以This开头的行需要推迟,直到获得That为止。在前一种情况下,您要删除它们之间的换行符,在后一种情况中,请按原样附加这两者。

with open('myfile.txt', 'r') as f:
    lines = f.readlines()

for index, line in enumerate(lines):
    if line.startswith('That') and index and lines[index - 1].startswith('This'):
        lines[index - 1] = lines[index - 1].replace('\n', ' ')

with open('myfile.txt', 'w') as f:
    f.writelines(lines)

您所需要做的就是删除换行符:writelines不会为您插入任何新的换行符。

虽然我选择将整个文件读入内存,但是您不需要这样做。一个相当标准的方法是打开一个临时文件,逐行快速写入该文件,然后将其移动以替换输入文件。在SO上已经可以找到如何执行此操作的详细信息。

答案 2 :(得分:0)

这里

with open('myfile.txt', 'r') as f:
    new_lines = []
    lines = [l.strip() for l in f.readlines()]
    for idx, line in enumerate(lines):
        if idx > 0:
            if line.startswith('This') and lines[idx - 1].startswith('That'):
                new_lines.pop()
                new_lines.append('{} {}'.format(line, lines[idx - 1]))
            else:
                new_lines.append(line)
        else:
            new_lines.append(line)

with open('myfile.txt', 'w') as f:
    for line in new_lines:
        f.write(line + '\n')

myfile.txt(之前)

afdfsdfdf dfsdfsdfs
That is my next line
This is my current line
sadgsdfg sadfgsgdfg
dfgdfgdfgdfgd
dfgdfgdfgdfgdf
That is my next line
sdftgertgertge
This is my current line
srgegergegyb  dfgtyrtyrty
That is my next line
This is my current line
eferer erwer

myfile.txt(之后)

afdfsdfdf dfsdfsdfs
This is my current line That is my next line
sadgsdfg sadfgsgdfg
dfgdfgdfgdfgd
dfgdfgdfgdfgdf
That is my next line
sdftgertgertge
This is my current line
srgegergegyb  dfgtyrtyrty
This is my current line That is my next line
eferer erwer