首页 > 解决方案 > 读取文本文件时未检测到某些行?

问题描述

text_file.txt

我得到了第一个打印语句的输出,但没有第二个打印语句的输出。请给我正确的代码,我需要编码或解码吗?请帮助我,我是 python3 的新手

标签: pythonfiletext

解决方案


这是您要实现的目标的更直接的实现。您可以将文件读入 Python 列表并通过 Python 列表索引引用每一行

with open('text_file.txt','r') as f: # automatically closes the file
    input_file = f.readlines() # Read all lines into a Python list

for line_num in range(len(input_file)):
    if "INBOIS BERCUKAI" in input_file[line_num]:
        print(input_file[line_num + 2]) # offset by any number you want
    # same for other if statements

推荐阅读