读取文件中的特定文本并分配给 python 中的变量

Reading a specific text in a file and assigning to a variable in python

我正在尝试 read/copy 文件中的特定文本并将其分配给变量。 文件(token.txt)内容为:

构建成功。

在这里,我想从这个文件中复制中间访问令牌的值 "token.txt" 并将其分配给一个名为 ttk 的变量。

要从文档中获取内容,请添加 open(token.txt, r)

要保存到文件,请使用

data=myfile.read().replace("mid-acess token:" "")

打印结果

print(data)

该文件似乎在第一行包含所需的标记,因此使用 open() 打开它,并将第一行读入变量:

with open('somefile.txt') as f:
    ttk = next(f).replace('Mid-access token:', '').strip()

现在变量 ttk 将包含令牌字符串。 str.replace() removes the prefix from the line and the str.strip() 是否可以删除任何周围的空格,例如行尾的换行符。

编辑

似乎标记行实际上出现在文件末尾,始终在 Mid-access token: 行之后。下面是一些代码,无论令牌在文件中的位置如何,它都会提取令牌:

ttk = None
with open('somefile.txt') as f:
    for line in f:
        if line.startswith('Mid-access token:'):
            ttk = next(f).strip()

print(ttk)