with open(filename) as f:
    while True:
        c = f.read(1)
        if not c:
            print("End of file")
            break
        print("Read a character:", c)
Answer from jchl on Stack Overflow
๐ŸŒ
Finxter
blog.finxter.com โ€บ how-to-read-one-character-at-a-time-from-a-file-in-python
How to Read One Character at a Time from a File in Python? โ€“ Be on the Right Side of Change
This method uses open() and read() and the walrus operator to read a flat-text file and display the contents one character at a time. In Python 3.8, a new syntax was defined: the := operator, affectionately known as the walrus operator.
Discussions

Reading a single character from a file in python? - Stack Overflow
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... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to read in one character at a time from a file in python? - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I want to read in a list of numbers from a file as chars one char at a time to check what that char is, whether it is a digit, a period, a + or -, an e or E, or some other char...and then perform whatever operation I want based on that. How can I do this using the existing code I already have? This is an example that I have tried, but didn't work. I am new to python... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How can I read a single character at a time?
How can I read just one character at a time More on discuss.python.org
๐ŸŒ discuss.python.org
0
0
June 24, 2024
python - How to read a single character from the user? - Stack Overflow
Another important detail is that ... 4 bytes from the input stream, as that's the maximum number of bytes a single character will consist of in UTF-8 (Python 3+). Reading only a single byte will produce unexpected results for multi-byte characters such as keypad arrows. ... import contextlib import os import sys import termios import tty _MAX_CHARACTER_BYTE_LENGTH = 4 @contextlib.contextmanager def _tty_reset(file_descriptor): ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-program-to-read-character-by-character-from-a-file
Python program to read character by character from a file - GeeksforGeeks
September 6, 2024 - Open a file in read mode that contains a string then use an Infinite while loop to read each character from the file the loop will break if no character is left in the file to read then Display each word of length 5 from each line in the text file.
๐ŸŒ
DataFlair
data-flair.training โ€บ blogs โ€บ python-program-to-read-character-by-character-from-a-file
Python Program to Read Character by Character From a File - DataFlair
February 29, 2024 - This tutorial is all about the ... for anyone starting with Pythonโ€”reading a file character by character. By exploring the details of working with files, weโ€™ll go through the step-by-step process of taking out each letter or symbol from a file....
๐ŸŒ
Quora
quora.com โ€บ How-do-I-read-the-first-character-of-a-line-in-Python
How to read the first character of a line in Python - Quora
Answer (1 of 7): If you mean a line of a file, you first open it, and when you run a for-loop over it, each line will be presented as a string. You can read it by addressing the first character of each line. [code]with open('file.txt', 'r') as f: for line in f: print(line[0]) [/code]
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-read-file-character-by-character
How to Read a file character by character in Python | bobbyhadz
April 10, 2024 - On each iteration of the while loop, we add the current character to a list. The list.append() method adds an item to the end of the list. Alternatively, you can use a for loop. ... Open the file in reading mode.
Find elsewhere
Top answer
1 of 16
244

Here's a link to the ActiveState Recipes site that says how you can read a single character in Windows, Linux and OSX:

    getch()-like unbuffered character reading from stdin on both Windows and Unix

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()
2 of 16
97
sys.stdin.read(1)

will basically read 1 byte from STDIN.

If you must use the method which does not wait for the \n you can use this code as suggested in previous answer:

class _Getch:
    """Gets a single character from standard input.  Does not echo to the screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()

(taken from http://code.activestate.com/recipes/134892/)

๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-read-file-until-specific-character
Read a file until a specific Character in Python | bobbyhadz
April 10, 2024 - If the end of the file has been reached, the file.read() method returns an empty string. On each iteration, we check if the current character is equal to the stop character. If the condition is met, we exit the loop, otherwise, we add the character ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ How-to-read-a-number-of-characters-from-a-text-file-using-Python
How to read a number of characters from a text file using Python?
May 11, 2023 - To start reading from a specific position in a file, seek() function is used. The read characters are printed using the print() function. The file is then closed using the close() function.
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ readchar
readchar ยท PyPI
Library to easily read single chars and keystrokes. Born as a python-inquirer requirement. ... Or download the source code from PyPi. ... from readchar import readkey, key while True: k = readkey() if k == "a": # do stuff if k == key.DOWN: # do stuff if k == key.ENTER: break ... Reads one character from stdin, returning it as a string with length 1.
      ยป pip install readchar
    
Published ย  Nov 04, 2024
Version ย  4.2.1
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-take-only-a-single-character-as-an-input-in-python
How to Take Only a Single Character as an Input in Python - GeeksforGeeks
April 28, 2025 - This approach will use the string indexing to extract only a single required character from the user input.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ inputoutput.html
7. Input and Output โ€” Python 3.14.4 documentation
If the end of the file has been reached, f.read() will return an empty string (''). >>> f.read() 'This is the entire file.\n' >>> f.read() '' f.readline() reads a single line from the file; a newline character (\n) is left at the end of the ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ does readline() return just a single character?
r/learnpython on Reddit: Does readline() return just a single character?
November 19, 2017 -

I was looking for a description of the difference between readlines() and readline(), and the top Google hit is this:

https://www.peterbe.com/plog/blogitem-040312-1

The author starts off by saying that readline() inputs a line of text, but then thanks commenters for pointing out that he'd got it "completely wrong" and that readline() inputs a character of text, and so he updated the blog post accordingly. Is that actually right?

Top answer
1 of 2
14
No, readline() reads data from the buffer until it sees a newline. >>> from io import StringIO >>> buffer = StringIO('Mary had a little lamb\nHer fleece was white as snow') >>> buffer.readline() 'Mary had a little lamb\n' However in modern day Python you don't need to use readline and readlines, you just use read() to read an arbitrary amount of characters (or the whole file by not supplying an argument) or iterate over the file which calls readline implicitly: >>> buffer = StringIO('Mary had a little lamb\nHer fleece was white as snow') >>> for line in buffer: ... print(line) ... Mary had a little lamb Her fleece was white as snow >>> Same with a file >>> with open('bla.txt') as fp: ... for line in fp: ... print(line) ... This is the first line This is the second line This is the third line If you want to have the lines of the file in a sequence like a list, use the list() constructor if you want to keep the newlines >>> with open('bla.txt') as fp: ... lines = list(fp) ... >>> lines ['This is the first line\n', 'This is the second line\n', 'This is the third line\n'] Or use a comprehension to strip them: >>> with open('bla.txt') as fp: ... lines = [l.strip() for l in fp] ... >>> lines ['This is the first line', 'This is the second line', 'This is the third line'] Another option is to use read() together with .splitlines(), which will also remove the newlines (as that complies with the general behavior of str.split()): >>> with open('bla.txt') as fp: ... lines = fp.read().splitlines() ... >>> lines ['This is the first line', 'This is the second line', 'This is the third line'] However this imposes the penalty of having to read the whole file first before splitting it into the list. This doesn't matter for a small file but for a big ass 100 MB file it certainly does. That's why a list comprehension is the proper way to do this. Of course if you want to handle the file line by line anyway you shouldn't read to a list first but rather iterate over the file itself.
2 of 2
3
This is really old. The real difference is that readline will read a single line, and readlines will read the entire file into memory and then return a list of lines.
๐ŸŒ
Swarthmore College
cs.swarthmore.edu โ€บ courses โ€บ CS21Labs โ€บ s17 โ€บ files.php
CS21 File I/O in Python
s = infile.readline() # read the second line of file outfile.write(s) # write s at the point after the first write left off At the end of the file is a special end of file character (EOF). In Python, calls to read method functions will return an empty string when they reach the end of the file: # read each line of a file and print to terminal s = infile.readline() while(s != ""): print(s) s = infile.readline() # read the next line ยท A file should be closed when you are done with it: ... readline(): read the next line in the file (from the current position up to and including the end of line char ('\n')) returns a string containing this line of the file:
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 3182306 โ€บ how-do-we-read-in-python-file-where-we-need-to-use-readlines-and-only-take-up-first-character-from-each-line-
How do we read in Python file where we need to use readlines and only take up first character from each line ? | Sololearn: Learn to code for FREE!
January 12, 2023 - Then, output the first character followed by no. of characters in each line: # open file in read mode file = open("filename.py", "r") # readlines() reads all lines one by one # and stores them as a list of strings lines = file.readlines() # loop through all lines for line in lines: # get first character of each line first_char = line[0] # count total characters in each line (excluding \n) char_count = len(line) - 1 # print first character followed by no. of characters in each line print(first_char + str(char_count)) ... Reza Mardani , it is not seen as very helpful when we are going to post a