Search code examples
pythonlinereadlines

Extract only the last line using read() function


I'm using the following code for some text analysis (I've more code for the analysis):

with open(os.path.join(root, file)) as auto:
    a = auto.read(50000)
    for line in auto:
      print(line)

My question is: how can I print only the last line of the file?

I try this approach but I don't think it is a good option since it doesn't return any message:

with open(os.path.join(root, file)) as auto:
            a = auto.read(50000)
            lines = a.readlines()
            last_line = lines[-1]
            for line in auto:
                print(last_line)

How can I print the last line of the file using auto.read()?

Thanks


Solution

  • Perhaps:

    list.txt:

    sdfs
    sdfs
    fg34
    345
    gn
    4564
    

    Hence:

    with open('list.txt') as fileObj:
        print(list(fileObj)[-1])
    

    Using pathlib:

    from pathlib import Path
    print(Path('list.txt').read_text().splitlines()[-1])
    

    OUTPUT:

    4564