繁体   English   中英

读取文本文件中的多行

[英]Read multiple lines in a text file

我正在逐行读取文本文件,当我遇到特定字符串时,我想将该行和以下两行存储在变量中。

infile = open('file.txt', 'r')

for line in infile:
    if line.startswith('X'):
        3_lines = readlines() 

infile.close()

有什么办法可以做到这一点。 我一直在尝试使用 next() 或 readlines() 来解决这个问题。 但我不知道如何让它工作。 任何建议将不胜感激。

您可以尝试使用列表,

results = []

infile = open('file.txt', 'r').readlines()

for line in infile:
    if line.startswith('t'):
        index = infile.index(line)

        for times in range(0, 3):
            results.append(infile[index + times])

print(results)

使用一个变量来存储还有多少行要读取:

infile = open('file.txt', 'r')

lines = []
lines_left = 0
for line in infile:
    # If there are any lines left to be read,
    # add the current line to lines and decrement
    # the remaining lines counter
    if lines_left > 0:
        lines.append(line)
        lines_left -= 1
        continue
    
    # If the expected line is found, add the
    # current line to lines and set how many lines
    # should be read in the next iterations of
    # the loop (in this case, 2)
    if line.startswith('X'):
        lines.append(line)
        lines_left = 2

infile.close()

暂无
暂无

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

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