Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python program to read character by character from a file

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given a text file. The task is to read the text from the file character by character.
Function used:
 

Syntax: file.read(length)
Parameters: An integer value specified the length of data to be read from the file.
Return value: Returns the read bytes in form of a string. 
 

Examples 1: Suppose the text file looks like this.
 

pythonfile-input1

 

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.

Example 2: REading more than one characters at a time. 
 

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

 


My Personal Notes arrow_drop_up
Last Updated : 20 Feb, 2023
Like Article
Save Article
Similar Reads
Related Tutorials