读取文本文件时,是否会检测到一些行?

2024-04-19 03:09:36 发布

您现在位置:Python中文网/ 问答频道 /正文

text_file.txt

I am getting the output for first print statement but not for second print statement.Please sugget me the correct code is there anything i have to encode or decode? please help me i m new to python3


Tags: thetotexttxtforoutputnotam
1条回答
网友
1楼 · 发布于 2024-04-19 03:09:36

这里有一个更直接的实现你想要达到的目标。您可以将文件读入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

相关问题 更多 >