0

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

Pedro Alves
  • 1,004
  • 1
  • 21
  • 47
  • you can count file lines (wc -l file) and seek at last line number – Wonka Apr 09 '19 at 14:43
  • 2
    Possible duplicate of [What is the most efficient way to get first and last line of a text file?](https://stackoverflow.com/questions/3346430/what-is-the-most-efficient-way-to-get-first-and-last-line-of-a-text-file) –  Apr 09 '19 at 14:49

2 Answers2

1

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
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

You wrote that

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

and then asked for a technique using read(). However, I think your approach is reasonable and it does work (though I suspect that the file you're reading has a blank line as the last line of the file). For example, this does indeed print the last line of the file:

import os
with open('test.py') as auto:
    lines = auto.readlines()
    last_line = lines[-1]
    print(last_line)
user212514
  • 3,110
  • 1
  • 15
  • 11