Python program to read character by character from a file

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 lenght 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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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()

chevron_right


Output

python-read-character

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output

python-read-character-by-character-1




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.