Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a single character from a file in python?

Tags:

python

file-io

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.

like image 804
Andy Avatar asked Nov 17 '25 20:11

Andy


1 Answers

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.

like image 155
Gareth Latty Avatar answered Nov 19 '25 08:11

Gareth Latty