Nima Falllah Nima Falllah - 1 month ago 9
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 = the_file.seek(n)
chars.read(s)

#do something with chars

result.write(chars)
n =+ 1
m =+ 2


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

01001010101000001000100010001100010110100110001001011100011010000001010001001


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

Answer

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:
    the_file.seek(n)
    chars = the_file.read(1)
    if not chars:
       break
    #do something with chars
    print chars
    result.write(chars)
    n +=2
the_file.close()