How to read a single character at a time from a file in Python?

kaushik picture kaushik · Jun 7, 2010 · Viewed 168.3k times · Source

Can anyone tell me how can I do this?

Answer

jchl picture jchl · Jun 7, 2010
with open(filename) as f:
  while True:
    c = f.read(1)
    if not c:
      print "End of file"
      break
    print "Read a character:", c