0
def readFile(filename):
    filename= open("filename.txt", 'r')
    readIt= filename.read(4)
    return readIt

When I call the above function it reads the four charcters from the textfile. But I want it to read through the whole file and group the first, second, third, and fourth together, fifth, sixth, seventh, eighth and so forth

I tried to use "with open" but I'm stuck on this. Pretty new to this. Input appreciated

czsffncv
  • 3
  • 2
  • 1
    Open the file in binary mode (`b`), not `r` mode. `r` mode opens it up as a text file, whereas you just want a raw binary file. – Akshat Mahajan Dec 21 '16 at 19:32
  • Sure, added, this, still only reads the same four bytes though @AkshatMahajan – czsffncv Dec 21 '16 at 19:43
  • Well, naturally. The documentation for `read(n)` clearly says you'll just get back the first `n` characters of the file stream - I don't see why you'd think it would do what you say. Either just do `read()` (no arguments) to get the whole file and loop through, or read four bytes at a time (again in a loop) and take the last character there. – Akshat Mahajan Dec 21 '16 at 19:48

3 Answers3

0

In the title you say bytes, but in your question it's characters. Assuming it's characters try doing

with open(filename) as f:
    content=f.read() #now it's all in memory
    groups = [ content[i:i+4] for i in range(0,len(content),4) ]

For more advanced and iterative solutions assuming you build a list holding the contents, check out this post.

Community
  • 1
  • 1
themistoklik
  • 880
  • 1
  • 8
  • 19
0

You can't reopen the file on every call. If you really need to do this as a series of calls, each of which returns a single 4-character chunk, then try something like this:

def readFile(filename):
    return filename.read(4)

file_ptr = open("filename.txt", 'r')
while <your ending condition>:
    four_chars = readFile(file_ptr)
Prune
  • 76,765
  • 14
  • 60
  • 81
0

I assume your file is called input_file.

So, in order to read bytes from your file you need to open your file in rb mode. Then you can follow the example below:

input_file:

hello there how are you ?

My example:

def read_bytes(fobj = "", byte = 0):
    with open(fobj, 'rb') as f:
        data = f.read()
        return [data[n:n+byte] for n in range(0, len(data), byte)]

Output:

print(read_bytes("input_file", 4)
>>> [b'hell', b'o th', b'ere ', b'how ', b'are ', b'you ', b'?\n']
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43