Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果下一行以某些单词开头,如何打印当前行的下一行?_Python - Fatal编程技术网

Python 如果下一行以某些单词开头,如何打印当前行的下一行?

Python 如果下一行以某些单词开头,如何打印当前行的下一行?,python,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 wi

我想在当前行上打印下一行,前提是当前行以文件的
“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

在检查第一行是否以“This”开头,第二行是否以“That”开头之前,您可能希望先将第一行和第二行存储到for循环外部的两个变量(
prev
cur
)中

编辑:我已经编辑了我的答案,以便它可以用于多行文件。对于多行,您可能希望将文件行存储到字符串
行的列表中,而不是使用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')
行=[]
将open(“myfile.txt”,“r”)作为f:
对于f中的行:
line.append(line.replace('\n','').replace('\r','')
将open(“myfile.txt”,“w”)作为f:
长度=长度(行)
i=0
而i
我们希望将不以
This开头的行直接附加到输出。以
This
开头的行需要延迟,直到您得到
that
或not。在前一种情况下,去掉它们之间的换行符,在后一种情况下,按原样附加两者

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。

此处

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(之前)

myfile.txt(之后)


嘿,谢谢!但是,如果我想保留文件中的其他行,它只打印文件中的“那一行”。@Madpysicator你说得对,我只能看到文件中最后一行“那一行”。@AlyssaAlex我已经更新了我的答案,以便它可以在多行上工作。让我知道它是否是您所期望的输出。我得到以下错误:对于索引,行中行:ValueError:要解包的值太多(预期为2)
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
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