我的文件中有这个:
2023-09-08 10:40:04 推特
2023-09-08 10:40:05 现实
我需要从最后一行获取第一个和第二个文本。
我尝试了这个,但它在第一个空格之前只得到文本:
with open("mujlist.txt", "r") as file:
lines = file.readlines()
if not lines:
print("There is nothing in your file")
else:
last_line = lines[-1].split(' ', 2)[0].strip()
print(last_line)
你知道要改变什么才能得到: 2023-09-08 10:40:05 ?
谢谢你
我需要从最后一行获取第一个和第二个文本..
如果您的文本文件相对较大,您可能需要考虑从末尾开始阅读:
with open("mujlist.txt", "rb") as f:
f.seek(-1, 2) # go the end of file
while f.read(1) != b"\n":
f.seek(-2, 1) # step back twice from current position
first, second, *_ = f.readline().decode().split() # change the sep if needed
输出:
print(first, second)
# 2023-09-08 10:40:05
print(" ".join([first, second]))
# 2023-09-08 10:40:05