-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
  • 3
    Welcome to Stack Overflow! Please take the [tour], read [what's on-topic here](/help/on-topic), [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953), and provide a [mre]. "Implement this feature for me" is off-topic for this site because SO isn't a free online coding service. You have to _make an honest attempt_, and then ask a _specific question_ about your algorithm or technique. – Pranav Hosangadi Aug 02 '21 at 19:51

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
  • 85
  • 2
  • 10
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])
Ani M
  • 1,868
  • 1
  • 2
  • 13
  • 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
  • 1,768
  • 14
  • 29