VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-to-read-character-by-character-from-a-file/

⇱ Python Program to Read Character by Character from a File - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Program to Read Character by Character from a File

Last Updated : 31 Oct, 2025

In this article, we will demonstrate how to read a file character by character using practical examples.

Example:

Input: Geeks
Output: G
e
e
k
s

Explanation: Iterated through character by character from the input as shown in the output.

Below is the sample text file:

👁 pythonfile-input1

Read character by character from a file

In this approach, we read one character at a time using the read(1) method, which is useful when processing files where each character needs to be analyzed individually, such as parsing or text analysis tasks.

Output 

👁 python-read-character

Explanation:

  • file.read(1): Reads one character at a time from the file.
  • while 1: Creates an infinite loop to process the file character by character.
  • if not char: break: Stops the loop when end of file (EOF) is reached.

Reading more than one character

This method reads a fixed number of characters (e.g., 5) at a time using read(n), which helps improve efficiency when working with larger files while still maintaining controlled reading.

Output 

👁 python-read-character-by-character-1
Explanation:

  • f.read(5): Reads 5 characters at a time.
  • while True: Loops until end of file.
  • if not c: break: Stops at EOF.

Related Articles:

Comment