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


Question

Can anyone tell me how can I do this?

1
62
2/10/2014 3:46:24 AM

Accepted Answer

with open(filename) as f:
  while True:
    c = f.read(1)
    if not c:
      print "End of file"
      break
    print "Read a character:", c
77
6/7/2010 9:19:44 AM

first open a file:

with open("filename") as fileobj:
    for line in fileobj:  
       for ch in line: 
           print ch

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon