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.
CodePudding user response:
The documenation provides an API, that can be used to solve that problem. You will need to do the following things in order:
- Open the file in text mode like in the example here.
- Change the file pointer to the last byte. This can be achieved using the
seek
memeber function of the file object. Use theSEEK_END
token with an offset of-1
to get one byte before the end of the file - Read one byte with the
read
function. - Print that byte.
- If you did not use a context manager (
with
keyword) while opening the file, you should useclose
to close the file before exiting the program
The trick here is to use the seek
method, that can be used to specify an offset relative to the end of the file.
CodePudding user response:
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:])
CodePudding user response:
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