python - 将文本文件的特定 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'所在的行,我想把这些行变成一个变量
但它只读取文本文件的第一行
我该如何解决
解决方案
@Maicon 有它,虽然在 python 中你甚至不需要全局变量,你可以desired_line
在if
语句中创建和设置,它的命名空间将扩展到包含语句的整个函数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()
推荐阅读
- python - SMTPSenderRefused 在 /accounts/signup/
- flutter - Flutter - 在小部件中访问 ThemeData.primarySwatch
- html - 使用带有 fontawesome 的关键帧
- bash - 如何在 git bash 上获得 pkill
- gdb - 在 gdb 中进行漂亮打印时如何访问数组?
- android - android studio和ndk如何使用“...android.googlesource.../external/icu/”?
- javascript - Chrome JavaScript 控制台
- html - 按钮 CSS 状态 - 在活动页面上保持悬停颜色
- python - 我收到此错误 simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- python - 如何在python中以这种形式输入?