Skip to main content
 首页 » 编程设计

Python 从文本中检索变量

2025年05月04日29pander-it

我正在尝试从文本文件中检索变量并将这些变量传递给 python。同样在一个文本文件中,我将包含如下内容:

Total Numbers: 22, Total Boxes: 33, Total Tickets: 62, Total Files: 107 
Total Numbers: 2, Total Boxes: 53, Total Tickets: 92, Total Files: 105 
Total Numbers: 3, Total Boxes: 13, Total Tickets: 22, Total Files: 137 
Total Numbers: 42, Total Boxes: 38, Total Tickets: 62, Total Files: 143 

我如何只从最后一行获取变量,例如我希望能够传递Total Numbers: 42,然后单独传递Total Boxes: 38,等等等等

例如假设我在 python 中有一个函数

def get_content(): 
f = open('test.txt') 
#not sure how to only retrieve last line 
my_number = # this is where i want to pass Total_numbers to get a value of 42 
f.close() 

请您参考如下方法:

如果文件不是太大,只需使用readlines 将行读入列表,使最后一行易于查找。有了该行后,将其拆分为逗号,然后再次拆分为空格以隔离值。我不确定您所说的“传递”它们是什么意思...所以这是一个示例,它仅提取 4 个值,将它们转换为整数并将它们作为 tuple 返回。

def get_content(): 
    """"Returns (numbers, boxes, tickets, files) for the last entry 
    in test.txt""" 
    with open('test.txt') as fp: 
        lines = fp.readlines() 
    # just in case there is an empty line at the end... 
    while lines and not lines[-1].startswith('Total Numbers'): 
        del lines[-1] 
    if lines: 
        # split on comma then take the number at the end and return 
        return tuple(int(part.split()[-1]) for part in lines[-1].strip().split(',')) 
 
print(get_content())