Python 读取文件的每一行并将其存储在您选择的单独变量中,无需多次 "with open" 调用

Python read and store each line of file in a separate variable of your choice without multiple "with open" calls

如问题标题中所述,我有下面的脚本读取 (在下面的代码中 <authfile> 只是一个占位符,可以包含任何安全身份验证文件像 Git) 并将内行作为凭据存储到用户选择的单独变量中:

import itertools

with open('.<authfile>', 'r') as <authfile>:
    gist_id = next(itertools.islice(<authfile>, 0, None)).rstrip('\n')
with open('.<authfile>', 'r') as <authfile>:
    token = next(itertools.islice(<authfile>, 1, None)).rstrip('\n')

但是正如您在代码中看到的那样,有一点 non-performance 因为我必须使用 2 with open 调用来按数字获取单独的行并存储到变量中。

我尝试阅读的样本数据文件看起来很像下面,但是 gist_ids 的顺序可能会改变 ,令牌我会尽可能多地保留它尽可能,所以你看在我的情况下最好只通过特定的行号读取这个文件,仍然对管理这个文件的建议持开放态度:

<gist_id1>
<gist_id2>
<gist_id4>
....
....
....
<token>

我怎样才能使它成为一个高性能的脚本,它触发单个 with open 调用并且仍然将每一行(没有换行符)存储到一个单独的变量中?另外我怎么能用最小的 code-change 来做到这一点?

如果您只是获取前两行,您只需要:

with open('.<authfile>', 'r') as authfile:
    gist_id = authfile.readline().rstrip()
    token = authfile.readline().rstrip()

不知道我在这里的回答是否符合最小代码更改的条件,但我能够找到从文件中读取任何特定行并将其存储在我希望的单独变量中的方法.

在 Tim Roberts 的启发和想法下,我在不使用 itertools 模块的情况下实现了它的工作,只是添加了另一种方法来进行正确的枚举。以下是我的回答:

def get_lines(fp, line_numbers):
    return (x for i, x in enumerate(fp) if i in line_numbers)
with open('.<authfile>', 'r') as <authfile>:
    lines = get_lines(<authfile>, [0,1])
    lines = list(lines)
    gist_id = lines[0].rstrip()
    token = lines[1].rstrip()

注意: 我可以通过将其添加到此数组 [0,1] 中来指定要读取的任何行,例如 [0,1,5,7,9].

如果有人需要进一步解释这个答案,请在这里发表评论。