0

In my case I am going to write some content to a file in bytearray format and tries to read the content that I have written . But here the problem is if I am not giving the seek function then the file content read is empty. What I understood is by default the reference point is at the beginning of the file which is similar to seek(0). Please help me to understand this problem. I will give you both scenarios as example here

Without seek command

filename = "my_file"

Arr = [0x1, 0x2]

file_handle = open(filename, "wb+")
binary_format = bytearray(Arr)
file_handle.write(binary_format)

#file_handle.seek(0) #Here commenting the seek(0) part
print("file_handle-",file_handle.read())
file_handle.close()

Output in the console

file_handle- b''

With seek command

filename = "my_file"

Arr = [0x1, 0x2]

file_handle = open(filename, "wb+")
binary_format = bytearray(Arr)
file_handle.write(binary_format)

file_handle.seek(0)
print("file_handle-",file_handle.read())
file_handle.close()

Output in the console is

file_handle- b'\x01\x02'
  1. Is the seek(0) is mandatory here even if by default it points to the beginning of file ?
Vishnu CS
  • 748
  • 1
  • 10
  • 24
  • 1
    This behavior is correct and documented in the [docs](https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects). After writing to the file, the position points to the 'end' in the file. You need to go to the beginning to read the entire file. – Maurice Meyer Jun 02 '20 at 08:45
  • @MauriceMeyer : Thanks. But is there any other possibility ? – Vishnu CS Jun 02 '20 at 08:55
  • What the problem calling `file_handle.seek(0)` after writing ? – Maurice Meyer Jun 02 '20 at 09:05
  • @MauriceMeyer The problem is I am using a library and there it is assigning the file handle before reading the content. If I am not giving `seek(0)` then the content will be read as empty. I don't want to modify the library. That's why I asked – Vishnu CS Jun 02 '20 at 09:10

0 Answers0