Python open file and get eveyrthing before second space

46 Views Asked by At

I have this in my file:
2023-09-08 10:40:04 twitter
2023-09-08 10:40:05 sreality

I need to get first and second text from the last line. I tried this but it get only text before first space:

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)

Do you have some idea what to change to get: 2023-09-08 10:40:05 ?

Thank you

2

There are 2 best solutions below

0
Timeless On

I need to get first and second text from the last line..

If your text-file is relatively large, you might want to consider reading it from the end :

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

Output :

print(first, second)
# 2023-09-08 10:40:05

print(" ".join([first, second]))
# 2023-09-08 10:40:05
0
SIGHUP On

Open the file. Read all lines. Locate last line. Locate first 2 tokens. Print them out.

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

Output:

2023-09-08 10:40:05

Note:

If the file doesn't contain at least one line, this will fail