1- """Write a user-defined function named count() that will read
2- the contents of text file named “happy.txt” and count
3- the number of lines which starts with either “I‟ or “M‟."""
1+ from pathlib import Path
2+ from typing import Tuple
43
5- import os
6- import time
7- file_name = input ( "Enter the file name to create:- " )
4+ def count_lowercase_chars ( file_path : str | Path ) -> Tuple [ int , int , int ]:
5+ """
6+ Counts lowercase, uppercase, and total alphabetic characters in a text file.
87
9- # step1 :
10- print ( file_name )
8+ Args :
9+ file_path: Path to the text file (can be a string or Path object).
1110
11+ Returns:
12+ Tuple containing (lowercase count, uppercase count, total alphabetic count).
1213
14+ Raises:
15+ FileNotFoundError: If the file does not exist at the specified path.
16+ PermissionError: If access to the file is denied.
17+ IsADirectoryError: If the path points to a directory instead of a file.
18+ """
19+ # Convert to Path object for consistent path handling
20+ file_path = Path (file_path )
21+
22+ # Check if file exists
23+ if not file_path .exists ():
24+ raise FileNotFoundError (f"File does not exist: { file_path } " )
25+
26+ # Check if it's a file (not a directory)
27+ if not file_path .is_file ():
28+ raise IsADirectoryError (f"Path is a directory, not a file: { file_path } " )
1329
14- def write_to_file (file_name ):
15-
16- if os .path .exists (file_name ):
17- print (f"Error: { file_name } already exists." )
18-
19- else :
20- with open (file_name , "a" ) as F :
30+ # Read file and count characters
31+ with open (file_path , 'r' , encoding = 'utf-8' ) as file :
32+ content = file .read ()
33+ lowercase = sum (1 for c in content if c .islower ())
34+ uppercase = sum (1 for c in content if c .isupper ())
35+ total_alpha = lowercase + uppercase
36+
37+ return lowercase , uppercase , total_alpha
2138
22- while True :
23- text = input ("enter any text" )
24- F .write (f"{ text } \n " )
39+ def main () -> None :
40+ """Main function to execute the file check and character counting."""
41+ # Specify the path to happy.txt (update this to your actual path!)
42+ # Example for Windows: r"C:\Users\YourName\1 File handle\File handle text\happy.txt"
43+ # Example for macOS/Linux: "/home/YourName/1 File handle/File handle text/happy.txt"
44+ file_path = r"1 File handle\File handle text\happy.txt" # Update this path!
2545
26- if input ("do you want to enter more, y/n" ).lower () == "n" :
27- break
46+ try :
47+ # Print current working directory for debugging
48+ print (f"Current working directory: { Path .cwd ()} " )
2849
29- # step2:
30- def check_first_letter ():
31- with open (file_name ) as F :
32- lines = F .read ().split ()
33-
34- # store all starting letters from each line in one string after converting to lower case
35- first_letters = "" .join ([line [0 ].lower () for line in lines ])
36-
37- count_i = first_letters .count ("i" )
38- count_m = first_letters .count ("m" )
39-
40- print (f"The total number of sentences starting with I or M are { count_i + count_m } " )
50+ lowercase , uppercase , total_alpha = count_lowercase_chars (file_path )
51+
52+ print ("\n === Character Count Results ===" )
53+ print (f"Lowercase letters: { lowercase } " )
54+ print (f"Uppercase letters: { uppercase } " )
55+ print (f"Total alphabetic characters: { total_alpha } " )
56+
57+ except FileNotFoundError as e :
58+ print (f"\n Error: { e } . Please check the file path." )
59+ except IsADirectoryError as e :
60+ print (f"\n Error: { e } " )
61+ except PermissionError :
62+ print (f"\n Error: No permission to access { file_path } " )
63+ except Exception as e :
64+ print (f"\n Unexpected error: { e } " )
4165
4266if __name__ == "__main__" :
43-
44- write_to_file (file_name )
45- time .sleep (1 )
46- check_first_letter ()
67+ main ()
0 commit comments