with open("abc.txt", "wb") as f:
f.write(b'Hello')
The above program will open a file in wb mode and write the binary data b’Hello’ to it. So, if we want to write binary data to a file and then read it, we can use the following program:
with open("abc.txt", "rb+") as f:
f.write(b'Hello')
f.seek(0)
print(f.read())
Here, we are trying to open a file, write data to it and then read the written data from the file in binary format. Please note that after the f.write() function is called, the file pointer will point to the end of the file. So, we are here using the f.seek(0) function to move the file pointer back to the beginning of the file.
The above program will print the following output:
b'Hello'
How to move the position of the file pointer in Python?
As I said, we can use the seek() method to move the position of the file pointer in Python.
with open("abc.txt", "rb") as f:
f.seek(1, 0)
print(f.read())
The f.seek() function here takes two arguments. The first argument is the offset. And, the second argument indicates whether the offset is from the beginning of the file, from the current position, or from the end of the file.
For example, f.seek(1,0) will move the file pointer to 1 byte ahead of the beginning of the file. Here, 0 indicates the offset is from the beginning of the file.
Similarly, f.seek(-1, 1) will move the file pointer to 1 byte behind the current position of the file pointer. The second argument 1 here indicates the offset is from the current position of the file pointer.
And, f.seek(-5,2) will move the file pointer to 5 bytes behind the end of the file. Here, the second argument 2 indicates the offset is from the end of the file.
So, in the above program, if the data written to the file “abc.txt” is b’Hello’, then the program will print the following output:
b'ello'








































0 Comments