Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 27 additions & 11 deletions 1 File handle/File handle text/question3.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,36 @@
the contents of text file named “happy.txt” and count
the number of lines which starts with either “I‟ or “M‟."""

import os
import time
file_name= input("Enter the file name to create:- ")

# step1:
def write_to_file():
with open("happy.txt", "a") as F:
while True:
text = input("enter any text")
F.write(
text + "\n"
) # write function takes exactly 1 arguement so concatenation
choice = input("do you want to enter more, y/n")
if choice == "n":
break
print(file_name)



def write_to_file(file_name):

if os.path.exists(file_name):
print(f"Error: {file_name} already exists.")

else:
with open(file_name, "a") as F:
while True:
text = input("enter any text")
F.write(
text + "\n"
) # write function takes exactly 1 arguement so concatenation
choice = input("do you want to enter more, y/n")
if choice == "n":
break

# write_to_file()

# step2:
def check_first_letter():
with open("happy.txt") as F:
with open(file_name) as F:
value = F.read()
count = 0
line = value.split()
Expand All @@ -29,4 +42,7 @@ def check_first_letter():
print("The total number of sentences starting with I or M are", count)

if __name__ == "__main__":

write_to_file(file_name)
time.sleep(1)
check_first_letter()