-2

Can someone please show me how I can read the first letter from the last line in a txt file in python. Sorry if the question is a little bit confusing this is my first question on stack overflow.

Lavi A
  • 3
  • 1

4 Answers4

2

This is a solution, although maybe not the best since it is not memory efficient since it reads all the contents of a text file. Reverse reading is probably too complex for what you are asking for.

with open('text.txt', 'r') as f:
    print(list(f)[-1][0])

MySlav
  • 151
  • 5
1
file_obj = open('myfile.txt')
the_text = file_obj.read()
*_, last_line = text.rsplit('\n', maxsplit=1)
first_char = last_line[0]
medecau
  • 124
  • 2
  • 12
0

A simple solution to accessing the last line of a file, though takes O(n) time, is using a basic for loop:

file = open("script.txt", "r")
last = ""
for line in file:
  last = line
print(last[0])
Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14
  • 2
    I think using `file.readlines()[-1]` as @MySlav did, is preferable to looping over the entire file. – Manusman Aug 02 '21 at 20:03
0

Small file solution. This opens the file, and iterates through lines until the file is completely iterated through.

with open('filename.txt') as f:
    for line in f:
        pass
    last_line_char = line[0]

Large file solution (also much faster). This takes advantage of the os.seek() module.

import os

with open('filename.txt', 'rb') as f:
    f.seek(-2, os.SEEK_END)
    while f.read(1) != b'\n':
        f.seek(-2, os.SEEK_CUR)
    last_line = f.readline().decode()
    last_line_char = last_line[0]

Code from here

blackbrandt
  • 2,010
  • 1
  • 15
  • 32