首页 > 解决方案 > 将文本文件的特定 int 行读取并获取到 python 上的变量中

问题描述

a_file = open('file.txt')
string = 'a word'
flag = 0
index = 0
for line in a_file:
    index += 1
    if string in line:
      break
index -= 1

lines_to_read = [index]

for position, line in enumerate(a_file):
    if position in lines_to_read:
        file = line
print(line)

我找到了'a word'所在的行,我想把这些行变成一个变量

但它只读取文本文件的第一行

我该如何解决

标签: python

解决方案


@Maicon 有它,虽然在 python 中你甚至不需要全局变量,你可以desired_lineif语句中创建和设置,它的命名空间将扩展到包含语句的整个函数if

a_file = open('file.txt')
string = 'a word'
for line in a_file:
    if string in line:
        desired_line = line
        break

print(desired_line)

a_file.close()

推荐阅读