Friday, December 27, 2024
Google search engine
HomeLanguagesPython program to read character by character from a file

Python program to read character by character from a file

Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it.

Example

Input: Geeks
Output: G
e
e
k
s
Explanation: Iterated through character by character from the input as shown in the output.

Read a file character by character in Python

In this article, we will look into a few examples of reading a file word by word in Python for a better understanding of the concept.

Read character by character from a file

Suppose the text file looks like this.
 

pythonfile-input1

Code Explanation: Open a file in read mode that contains a character then use an Infinite while loop to read each character from the file and the loop will break if no character is left in the file to read then Display each character from each line in the text file.

Python3




# Demonstrated Python Program
# to read file character by character
file = open('file.txt', 'r')
 
while 1:
     
    # read by character
    char = file.read(1)         
    if not char:
        break
         
    print(char)
 
file.close()


Output 
 

python-read-character

Time complexity: O(n), where n is the number of characters in the file.
Auxiliary space: O(1), as the program reads and prints characters one at a time without storing them in memory.

Reading more than one character

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.

Python3




# Python code to demonstrate
# Read character by character
with open('file.txt') as f:
     
    while True:
         
        # Read from file
        c = f.read(5)
        if not c:
            break
 
        # print the character
        print(c)


Output 

python-read-character-by-character-1

RELATED ARTICLES

Most Popular

Recent Comments