0

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.

Rob
  • 1
  • 1

3 Answers3

1

The documenation provides an API, that can be used to solve that problem. You will need to do the following things in order:

  1. Open the file in text mode like in the example here.
  2. Change the file pointer to the last byte. This can be achieved using the 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 file
  3. Read one byte with the read function.
  4. Print that byte.
  5. If you did not use a context manager (with keyword) while opening the file, you should use close 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.

Jakob Stark
  • 3,346
  • 6
  • 22
1

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:])
  • 1
    Good answer. Note that this loads the entire file into memory. For small and medium sized files this will not be a problem though. Also note that you have not to convert all the bytes to binary representation, if you just want to print the last one. Instead of the last 4 lines you could just write `print(bin(byte_array[-1]))` or `print(hex(byte_array[-1]))` for hexadecimal representation. – Jakob Stark Mar 01 '22 at 12:24
  • @JakobStark good points. Did not care about the optimizing I must say, but you are totally right. – JuliusMoehring Mar 01 '22 at 12:31
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

DarkKnight
  • 19,739
  • 3
  • 6
  • 22