Home > OS >  Python - How do I read the most recent line added to a file?
Python - How do I read the most recent line added to a file?

Time:04-18

I want to read the most recent line added to a file

myfile = open("Username.txt", "r")
lines = myfile.readline()
GetTopic = print lines(recent line)
if GetTopic == "....":
    then ......

CodePudding user response:

Files don't hold a history of changes. The Operating System may store the last time a file changed, but there is nothing like "most recent line added".

Therefore, what you want to do is impossible.

EDIT : If you're referring to last line of the file, here is how you do it.

myfile = open("Username.txt", "r")
lines = myfile.readlines()
print(lines[-1])

Will return the last line of the file.

EDIT 2:

If the file is very large and won't fit into memory :

myfile = open("Username.txt", "r")
last_line = ""
for line in myfile:
  last_line = line
print(last_line) # Will hold last line in the file

CodePudding user response:

As @0xRyN mention if you want to update line as the file updated, you have to deal with os level code. But if you want just last line as soon as open file you can use this

    ....
    Lines = file1.readlines() 
    lastLine = Lines[-1] 
    print(lastLine)

    

CodePudding user response:

with open("test.txt","r") as file:
    lines = file.readlines()
print(lines[-1])

CodePudding user response:

Three ways:

Use a loop:

with open(ur_file) as f:
    for line in f:
        pass
# end of the with block, line will be the last line

Use a deque with some max that is reasonable and take the last:

def tail(filename, n=10):
    'Return the last n lines of a file'
    with open(filename) as f:
        return deque(f, n)

For HUGE files you might want to seek to the end, rewind a bit, then read lines:

offset=2000 #size known to contain a line break
with open(ur_file) as f:
    f.seek(0, 2)
    end=f.tell()
    f.seek(end-offset)
    last=f.readlines()[-1]
  • Related