Search code examples
pythonfile-iocharacter

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


In Python, given the name of a file, how can I write a loop that reads one character each time through the loop?


Solution

  • with open(filename) as f:
        while True:
            c = f.read(1)
            if not c:
                print("End of file")
                break
            print("Read a character:", c)