Excercise on file handling

  1. Write a function in python to read the content from a text file “poem.txt” line by line and display the same on screen.

2.Write a function in python to count the number of lines from a text file “story.txt” which is not starting with an alphabet “T”.

def display_poem(filename):
with open(filename, ‘r’) as file:
for line in file:
print(line, end=‘’)
filename = “poem.txt”
display_poem(filename)

1 Like

def read_poem(file_name):
try:
with open(file_name, ‘r’) as file:
for line in file:
print(line.strip())
except FileNotFoundError:
print(f"The file ‘{file_name}’ does not exist.")

file_name = “poem.txt”
read_poem(file_name)

1 Like

very good Deepak. keep it up

very good pavan. keep it up

def display_poem(filename):
with open(filename, ‘r’) as file:
for line in file:
print(line, end=‘’)
filename = “poem.txt”
display_poem(filename)

1 Like

very good rejesh, keep practicing

2

def count(filename):
count = 0
with open(filename, ‘r’) as file:
for line in file:
if line.startswith(‘T’):
count += 1
return count

filename = “story.txt”
line_count = count(filename)
print(f"Number of lines not starting with ‘T’: {line_count}")

1 Like

really appriciated deepak. but here if line[0] you can use instead of line.startswith

def count_lines_not_starting_with_T(filename):
try:
file = open(filename, ‘r’)
count = 0

    for line in file:
        if not line.strip().lower().startswith('t'):
            count += 1
    
    file.close()
    
    return count
except FileNotFoundError:
    return -1 
except Exception as e:
    print(f"An error occurred: {e}")
    return -2  

filename = “story.txt”
result = count_lines_not_starting_with_T(filename)

if result == -1:
print(f"Error: File ‘{filename}’ not found.“)
elif result == -2:
print(“An error occurred while processing the file.”)
else:
print(f"Number of lines not starting with ‘T’: {result}”)

1 Like

good. keep practicing

def countLinesNotStartingWithT(filename):
    try:
        # Open the file for reading
        with open(filename, 'r') as file:
            line_count = 0  # Initialize the line count

            # Loop through each line in the file
            for line in file:
                line = line.strip()  # Remove leading and trailing whitespace
                print(line)  # Display the line

                # Check if the line does not start with 'T' or 't'
                if not line.startswith(('T', 't')):
                    line_count += 1

        # Print the count of lines not starting with 'T'
        print(f"Number of lines not starting with 'T': {line_count}")

    except FileNotFoundError:
        print(f"File '{filename}' not found.")

# Call the function with the file name
countLinesNotStartingWithT("poem.txt")