My question would be if there was any other way besides below to iterate through a file one character at a time?
with open(filename) as f:
while True:
c = f.read(1)
if not c:
print "End of file"
break
print "Read a character:", c
Since there is not a function to check whether there is something to read like in Java, what other methods are there. Also, in the example, what would be in the variable c when it did reach the end of the file? Thanks for anyones help.
Another option is to use itertools.chain.from_iterable():
import itertools
with open("test.txt") as f:
for c in itertools.chain.from_iterable(f):
print(c)
chain.from_iterable makes an iterable that returns elements from the first iterable in the given iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Normally this is used to flatten out lists of lists, but in this case, it allows you to ignore the lines.
Whether this is really any better than nested loops is another matter (it'll be a little faster, but that's unlikely to matter), but worth mentioning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With