tags:

views:

95

answers:

5

I want to read a single character at a time from a file in python.

Can anyone tell me how can I do this?

A: 

Have you tried f.read(1)?

kotlinski
+3  A: 

Python itself can help you with this, in interactive mode:

>>> help(file.read)
Help on method_descriptor:

read(...)
    read([size]) -> read at most size bytes, returned as a string.

    If the size argument is negative or omitted, read until EOF is reached.
    Notice that when in non-blocking mode, less data than what was requested
    may be returned, even if no size parameter was given.
Mattias Nilsson
@Mattias: I agree with the sentiment, but perhaps this is better suited as a comment to the OP?
Mike Boers
Might be, but I think all that text would look messy in a comment.
Mattias Nilsson
+5  A: 
with open(filename) as f:
  while True:
    c = f.read(1)
    if not c:
      print "End of file"
      break
    print "Read a character:", c
jchl
A: 

Just read a single character

f.read(1)
David Sykes
+1  A: 

Just:

myfile = open(filename)
onecaracter = myfile.read(1)
joaquin