You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python代码提取文件最后一行的日期与时间部分?

问题描述

我的文件内容如下:

2023-09-08 10:40:04 twitter
2023-09-08 10:40:05 sreality

我需要提取最后一行的前两部分(即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)

请问需要怎么修改代码才能实现需求?

修改方案

问题出在split(' ', 2)[0]这里——你只取了分割后的第一个元素。要拿到前两部分的组合,调整一下取值逻辑就行:

方法一:分割后取前两部分再拼接

直接修改else块的代码:

else: 
    # 按空格分割成最多3段,取前两段后用空格拼接
    parts = lines[-1].split(' ', 2)[:2]
    result = ' '.join(parts).strip()
    print(result)

split(' ', 2)会把整行按空格拆成最多3块(日期、时间、平台名),[:2]取前两块,再用空格拼起来就是你要的日期时间组合。

方法二:定位第二个空格截取内容

如果需要更严谨地处理格式异常的情况,可以用索引定位:

else: 
    last_line = lines[-1].strip()
    # 找到第一个和第二个空格的位置
    first_space = last_line.find(' ')
    second_space = last_line.find(' ', first_space + 1)
    if second_space != -1:
        result = last_line[:second_space].strip()
        print(result)
    else:
        print("该行格式不符合预期")

这种方法会先确认行里有两个空格,再截取到第二个空格之前的内容,避免格式不对时出错。

内容的提问来源于stack exchange,提问作者Mirek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 16:23:25