python
I have a text file (.txt) and I need to print to the last byte of the txt. how I do that ? When I do not know the size of the document.
The documenation provides an API, that can be used to solve that problem. You will need to do the following things in order:
seek
memeber function of the file object. Use the SEEK_END
token with an offset of -1
to get one byte before the end of the fileread
function.with
keyword) while opening the file, you should use close
to close the file before exiting the programThe trick here is to use the seek
method, that can be used to specify an offset relative to the end of the file.
The following should work:
with open("text.txt") as file:
text = outfile.read()
byte_array = bytearray(text, "utf8")
print(byte_array[-1:])
If you need the binary representation
with open("text.txt") as file:
text = outfile.read()
byte_array = bytearray(text, "utf8")
binary_byte_list = []
for byte in byte_array:
binary_representation = bin(byte)
binary_byte_list.append(binary_representation)
print(binary_byte_list[-1:])
You could do it like this using seek which obviates the need to read the entire file into memory:
import os
with open('foo.txt', 'rb') as foo:
foo.seek(-1, os.SEEK_END)
b = foo.read()
print(b)
In this case the last character is newline and therefore:
Output:
b'\n'
Note:
File opened in binary mode