From 914edd09df10057c3d1130a3c37d9114abeddaa4 Mon Sep 17 00:00:00 2001 From: muzakkirsaifi123 Date: Fri, 31 Mar 2023 16:49:08 +0530 Subject: [PATCH] update the code as per user need --- 1 File handle/File handle text/question3.py | 38 +++++++++++++++------ 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/1 File handle/File handle text/question3.py b/1 File handle/File handle text/question3.py index 598c57798c0..713dc7f917a 100644 --- a/1 File handle/File handle text/question3.py +++ b/1 File handle/File handle text/question3.py @@ -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() @@ -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()