Nima Falllah Nima Falllah - 4 months ago 27
Python Question

How to loop over every 2 characters in a file in python

I'm trying to loop over every 2 character in a file, do some tasks on them and write the result characters into another file.

So I tried to open the file and read the first two characters.Then I set the pointer on the 3rd character in the file but it gives me the following error:

'bytes' object has no attribute 'seek'

This is my code:

the_file = open('E:\\test.txt',"rb").read()
result = open('E:\\result.txt',"w+")

n = 0
s = 2
m = len(the_file)

while n < m :

chars =

#do something with chars

n =+ 1
m =+ 2

I have to mention that inside
is only integers (numbers).
The content of
is a series of binary data (0's and 1's) like this:


Although it's not the point here, but just want to replace every 2 character with something else and write it into


Use the file with the seek and not its contents
Use an if statement to break out of the loop as you do not have the length
use n+= not n=+ finally we seek +2 and read 1
Hopefully this will get you close to what you want. Note: I changed the file names for the example

the_file = open('test.txt',"rb")
result = open('result.txt',"w+")

n = 0
s = 2
while True:
    chars =
    if not chars:
    #do something with chars
    print chars
    n +=2