Python program to read character by character from a file
Last Updated :
28 Aug, 2023
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.
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
file = open ( 'file.txt' , 'r' )
while 1 :
char = file .read( 1 )
if not char:
break
print (char)
file .close()
|
Output
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
with open ( 'file.txt' ) as f:
while True :
c = f.read( 5 )
if not c:
break
print (c)
|
Output
Share your thoughts in the comments
Please Login to comment...