提问人:Mirek 提问时间:9/8/2023 最后编辑:Mirek 更新时间:9/8/2023 访问量:42
Python 打开文件并获取第二个空格之前的 eveyrthing
Python open file and get eveyrthing before second space
问:
我的文件中有这个: 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 ?
谢谢
答:
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
注意:
如果文件不包含至少一行,则此操作将失败
评论
last_line=' '.join(lines[-1].split(' ')[:2])