Python 打开文件并获取第二个空格之前的 eveyrthing

Python open file and get eveyrthing before second space

提问人:Mirek 提问时间:9/8/2023 最后编辑:Mirek 更新时间:9/8/2023 访问量:42

问:

我的文件中有这个: 2023-09-08 10:40:04 twitter
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

谢谢

python 文件 条带 读取行

评论

0赞 Sembei Norimaki 9/8/2023
@Mirek这是什么?如果是与问题相关的信息,请编辑问题并将其发布在那里,而不是在评论中。据我所知,您的文件不包含 text1 text2 text3。你必须在你的问题中发布一个可重复的例子,如果你把通用文本放在你所问的问题上,你会得到答案,这可能对你的实际数据根本不起作用。
0赞 Mirek 9/8/2023
好的,您的代码正在运行,是否可以以这种形式运行?2023-09-08 10:40:05
1赞 Sembei Norimaki 9/8/2023
好的,你的文件是这样的。在执行我的代码时,你应该得到 [“2023-09-08”, “10:40:05”],这就是你要问的。你想把它合并为一个字符串吗?然后使用 .join: 联接列表的元素last_line=' '.join(lines[-1].split(' ')[:2])

答:

1赞 Timeless 9/8/2023 #1

我需要从最后一行获取第一个第二个文本。

如果你的文本文件相对较大,你可能要考虑从结尾阅读它:

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
1赞 CtrlZ 9/8/2023 #2

打开文件。阅读所有行。找到最后一行。找到前 2 个令牌。打印出来。

with open('mujlist.txt') as file:
    print(*file.readlines()[-1].split()[:2])

输出:

2023-09-08 10:40:05

注意:

如果文件不包含至少一行,则此操作将失败