I'm trying to set a variable to the last character of a file. I am using Python, and I'm fairly new to it. If it is of any importance, my code appends a random number between 2 and 9 to the end of an HTML file. In a separate function, I want to set the last character of the HTML file (the last character being the random number between 2 and 9) to a variable, then delete the last character (as to not affect the function of the HTML). Doe's anyone know how I could do this? I can attach my code below if needed, but I chose not to as it is 50 lines long and all 50 lines are needed for full context.
Asked
Active
Viewed 4,347 times
2
-
1Do you want to set the last or get the last? – enzo Jun 02 '21 at 19:39
-
1"My code is too long to share": That's why we ask for a [mre]! – Pranav Hosangadi Jun 02 '21 at 19:40
-
@enzo I want to get the last character from the HTML file, define a variable as "var = lastChar", then delete the last character of the HTML file. – Jun 02 '21 at 19:40
-
@PranavHosangadi As stated in my question, all 50 lines are needed for full context of the problem. I could simplify code to comments which represent function, but I feel this would cause further confusion. – Jun 02 '21 at 19:41
-
@TBQTLS 50 lines isn't really a lot. But an example would help – M Z Jun 02 '21 at 19:44
-
IMO a [mre] for your problem would only need a file that is a couple lines long and your code to read the last character of the file (and this code should only be a few lines anyway). The point of a MRE is to isolate your issue by replicating it with as little code as possible. – Pranav Hosangadi Jun 02 '21 at 19:47
-
2Does this answer your question? [Only read the last character in a .txt file](https://stackoverflow.com/questions/27141694/only-read-the-last-character-in-a-txt-file) – Jab Jun 02 '21 at 19:48
3 Answers
3
try this,
"a.txt" file has number 1, 3, 4, 5
Below code will read the file and pulls out last character from the file.
file = open('a.txt','r')
lines = file.read()
print(lines[-1])
=> 5

Rima
- 1,447
- 1
- 6
- 12
-
-
2
-
@ch2019 This solves my problem with the exception of the fact that this code does not delete the last character. I will mark this as answered. Thank you for your help. – Jun 02 '21 at 19:48
-
@TBQTLS If this code does not fully solve your problem, why did you accept it? – enzo Jun 02 '21 at 20:05
-
Shouldn't the file be closed after opening and reading it? – generic_stackoverflow_user Jun 02 '21 at 20:43
-
Python automatically closes a file. However, it is good practice to close file. – Rima Jun 02 '21 at 20:49
2
Using @Jab's answer from the comment above as well as some assumptions, we can produce a more efficient solution to finding the last character and replacing it.
The assumptions that are made are common and most likely will be valid:
- You will know whether there is a newline character at the very end of the file, or whether the random number is truly the last character in the file (meaning accounting for whitespace).
- You know the encoding of the file. This is valid since almost all HTML is utf-8, (can be utf-16), and since you are the one editing it, you will know. Most times the encoding won't even matter.
So, this is what we can do:
with open("test.txt", "rb+", encoding='utf-8') as f:
f.seek(-2, 2)
# -1 or -2, may change depending on whitespace characters at end of the file
var = f.read(1) # read one byte for a number
f.seek(-1,1)
print("last character:", str(var, 'utf-8'))
f.write(bytes('variable', 'utf-8')) # set whatever info here
f.write(bytes('\n', 'utf-8')) # you may want a newline character at the end of the file
f.truncate()
This is efficient because we actually don't have to iterate through the entire file. We iterate through just the last character, once to read and once to write.

M Z
- 4,571
- 2
- 13
- 27
1
You can do something like that:
# Open the file to read and the file to write
with open('file.txt'), open('new_file.txt', 'w+') as f_in, f_out:
# Read all the lines to memory (you can't find the last line lazily)
lines = f_in.readlines()
# Iterate over every line
for i, line in enumerate(lines):
# If the current index is the last index (i.e. the last line)
if i == len(lines) - 1:
# Get the last character
last_char = line[-1]
# Write to the output file the line without the last character
print(line[:-1], file=f_out, end='')
else:
# Write to the output file the line as it is
print(line, file=f_out, end='')
# Print the removed char
print(last_char)
If you don't want to create a new file, you can load all the file to memory as we're currently doing:
# Read all the lines into memory
with open('file.txt') as f:
lines = f.readlines()
# Replace the lines inside the list using the previous logic
for i, line in enumerate(lines):
if i == len(lines) - 1:
last_char = line[-1]
lines[i] = line[:-1]
else:
lines[i] = line
# Write the changed lines to the same file
with open('file.txt', 'w+') as f:
print(''.join(lines), file=f, end='')
# Print the removed char
print(last_char)

enzo
- 9,861
- 3
- 15
- 38