Python Tutorial | Python Data File Handling 6

File reading: Character By Character

Question: 1
Python program to read the contents of a file character by character and display them?(Method:1)
Sol:

def file_read():
     f=open("abc.txt")
     while True:
         c=f.read(1)
         if not c:
             #print("end of file")
             break
         print(c,end='')

#function calling
file_read()

Question: 2
Python program to read the contents of a file character by character and display them?(Method : 2)
Sol:

def file_read1():
     with open("abc.txt") as f:
         while True:
             c=f.read(1)
             if not c:
                 #print("end of file")
                 break
             print(c,end='')
#function calling
file_read1()

Question: 3
Python program to read the contents of the file “abc.txt” and print its length.
Sol:

def count_len():
     le=0
     with open("abc.txt") as f:
         while True:
             c=f.read(1)
             if not c:
                 break
             print(c,end='')
             le=le+1
         print("length of file ",le)
 #function calling
 count_len()

Question : 4
Python program to read the contents of the file “story.txt”. Further count and print total lower case alphabets in the file
Sol:

def count_lower():
     lo=0
     with open("story.txt") as f:
         while True:
             c=f.read(1)
             if not c:
                 break
             print(c,end='')
             if(c>='a' and c<='z'):
                 lo=lo+1
         print("total lower case alphabets ",lo)
 function calling
 count_lower()

Question: 5
Python program to read the contents of the file “story.txt”. Further, count and print total upper case alphabets in the file.
Sol:

def count_upper():
     u=0
     with open("story.txt") as f:
         while True:
             c=f.read(1)
             if not c:
                 break
             print(c,end='')
             if(c>='A' and c<='Z'):
                 u=u+1
         print("total upper case alphabets ",u)
 function calling
 count_upper()

Python Basic Programming Tutorial

Python Introduction     Getting started in Python Programming      Python propgramming fundamentals     Python Operators    Python If Condition     Python for loop    Python range construct      Python While loop    break and continue statements     Different looping techniques     Python List     Python String     Python Functions    Python Inbuilt Functions     Python Recursion     Using Python Library     Python Tuples     Python Dictionary     Python Sets     Python Strings     Python Exception Handling     Python Data File Handling

Visitor Counter

0056717