Martin Martin - 1 month ago 6
Python Question

Python : read text file character by character in loop

For example, there's a text file which contains numbers from 0 to 9:


0123456789


Using the following function, I'd like to get output like this:

>>> print_char('filename')
0
>>> print_char('filename')
1
>>> print_char('filename')
2
.
.
.
>>> print_char('filename')
9


That means, every time I call the function it returns the next number.

Here's my function:

def print_char(filename):
f = open(filename, 'r')
while True:
char=f.read(1)
if not char:
break
print(char)


...and the output I've got:

>>> print_char('filename')
0
1
2
3
.
.
.
9


So, how to create the function which will return character by character on every call?

Answer

I'd approach this differently, and make a function that takes in a filename that returns a generator:

def reader(filename):
    with open(filename) as f:
        while True:
            # read next character
            char = f.read(1)
            # if not EOF, then at least 1 character was read, and 
            # this is not empty
            if char:
                yield char
            else:
                return

Then you need to give the filename only once

r = reader('filename')

And the file is kept opened for much faster operation. To fetch next character, use the next built-in function

print(next(r))  # 0
print(next(r))  # 1
...

You can also use itertools, such as islice on this object slice characters, or use that in a for loop:

# skip characters until newline for c in r: if r == '\n': break

Comments