我试图从文本文件中检索变量并将这些变量传递给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()
答案 0 :(得分:2)
如果文件不是太大,只需使用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())
答案 1 :(得分:2)
我怎样才能从最后一行检索变量
要检索数据文件中的最后行,您可以尝试
import subprocess
last_line = str(subprocess.check_output(['tail', '-1', 'data.txt']))
从那里,分裂,例如如 tdelaney 所述,将提供所需的值。
答案 2 :(得分:1)
如果您只想阅读最后一行,然后输出数字42:
>>> f = open('somefile.txt')
>>> f.seek(-2, 2)
>>> while f.read(1) != b"\n":
... f.seek(-2, 1)
...
>>> last_line = f.readline()
>>> last_line.split(',', 1)[0].split(':')[1].strip()
'42'
现在,如果您希望以稍后可以操作它的方式获取所有数据,则需要做更多的工作:
>>> import re
>>> e = r'Total (\w+): (\d+)'
>>> data = dict(re.findall(e, last_line))
>>> data['Tickets']
'62'