首页 > 解决方案 > 如果我知道它在 python 中的编号,我可以在文本文件中找到一行吗?

问题描述

word = "some string"
file1 = open("songs.txt", "r")
flag = 0
index = 0
for line in file1:
    index += 1
    if word in line:
        flag = 1
        break
    if flag == 0:
        print(word + " not found")
    else:

#我想不仅打印有字符串的行,还要打印上一行和下一行 print(?) print(line) print(?)
file1.close()

标签: pythonfile

解决方案


使用contents = file1.readlines()它将文件转换为列表。

然后,循环遍历contents,如果word找到,就可以打印contents[i], contents[i-1], contents[i+1]. word如果是在第一行,请确保添加一些错误处理,就像contents[i-1]抛出和错误一样。


推荐阅读