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.
Asked
Active
Viewed 192 times
4 Answers
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
-
1Calling `readlines` is unnecessary, `list(f)` will return the lines as a list as well. – Einliterflasche Aug 02 '21 at 20:04
-
True, thanks for the suggestion, will edit the answer. – MySlav Aug 02 '21 at 20:14
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
-
Reading the whole file just to split it is unnecessary. Using`file.readlines()` or `list(file)` is much easier. – Einliterflasche Aug 02 '21 at 20:08
-
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
-
2I 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