如何使用 Python 从文件中检索特定值

how to retrieve specific value from file using Python

我有一个文本文件,文件末尾包含几行我有以下行:"Total: 235267878" 我的问题是:如何检索特定值 (235267878) 并将其设置为变量?

谢谢!

由于您没有指定文件的长度,我们可以遍历文件:

with open('test.txt', 'r') as file:
    for line in file:
        if 'Total:' in line:
            totalValue = line.split(':')[-1].strip()

print(totalValue)

在此解决方案中,我假设我们要查找的行始终具有 Total: {number} 的形式。我们以 只读模式 打开文件并遍历行(在我的示例中,文件名为 test.txt)。找到包含总值的行后,我们将其拆分并删除可能的空格以获得数字。变量 totalValue 包含您要查找的数字。