Python Tutorial | Python Data File Handling 11

Question: 5
#Python Program to read a file “story.txt” line by line and display the contents. count and print total lines not starting with “A” or “a” in the file
#Note:
#Using the above program we can display line not starting with any character.
Sol:

Method:1

filepath = 'story.txt'
with open(filepath) as fp:
    line = fp.readline()
    cnt = 1
    while line:
        if not (line[0]=='a' or line[0]=='A'):
            #print(line)
            print("Line {}: {}".format(cnt, line.strip()))
            cnt=cnt+1
        line = fp.readline()

Method:2

filepath = 'story.txt'
with open(filepath) as fp:
    line = fp.readline()
    cnt = 1
    while line:
        if not (line[0]=='a' or line[0]=='A'):
            #print(line)
            print(cnt,"  ",line,end='')
            cnt=cnt+1
        line = fp.readline()

Question: 6
#Python Program to read a file “story.txt” line by line and display the contents. count and print total lines not starting with vowels (A,a,E,e,I,i,O,o,U,u) in the file
#Note:
#Using the above program we can display line not starting with any character.
Sol:

Method:1

filepath = 'story.txt'
vowels="AEIOUaeiou"
with open(filepath) as fp:
    line = fp.readline()
    cnt = 1
    while line:
        if not (line[0] in vowels):
            #print(line)
            print("Line {}: {}".format(cnt, line.strip()))
            cnt=cnt+1
        line = fp.readline()

Method:2

filepath = 'story.txt'
vowels="AEIOUaeiou"
with open(filepath) as fp:
    line = fp.readline()
    cnt = 1
    while line:
        if not(line[0] in vowels):
            #print(line)
            print(cnt,"  ",line,end='')
            cnt=cnt+1
        line = fp.readline()

Question: 7
#Python Program to read a file “data.txt” line by line and display the contents. count and print total words in each line.
Sol:

def count_words():
     with open("data.txt") as f:
         i=0
         for line in f:
             i=i+1
             w=0
             for word  in line.split():
                 print(word)
                 w=w+1
             
             print("Line ",i," has total words ",w)
#function calling
count_words()

Visitor Counter

0051050