Skip to content

Commit 6667edd

Browse files
committed
Update
1 parent 7b09272 commit 6667edd

File tree

5 files changed

+170
-60
lines changed

5 files changed

+170
-60
lines changed

1 File handle/File handle text/input,output and error streams.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import sys
2-
from typing import NoReturn, List
2+
from typing import NoReturn
33

44

55
def read_and_print_file(file_path: str) -> None:

1 File handle/File handle text/question 2.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import sys
2-
from typing import List, Tuple, Optional
1+
from typing import List, Tuple
32

43

54
def display_short_words(file_path: str) -> Tuple[List[str], int]:
Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,49 @@
1-
"""Write a function in python to count the number of lowercase
2-
alphabets present in a text file “happy.txt”"""
1+
from collections import Counter
2+
from pathlib import Path
33

4-
from counter import Counter
4+
def count_lowercase_chars(file_path: str | Path = "happy.txt") -> tuple[int, int, int]:
5+
"""
6+
Counts the number of lowercase letters, uppercase letters, and total alphabetic characters in a text file.
57
6-
def lowercase():
8+
Args:
9+
file_path (str | Path): Path to the text file. Defaults to "happy.txt".
710
8-
with open("happy.txt") as F:
9-
word_counter = Counter(F.read())
11+
Returns:
12+
tuple[int, int, int]: A tuple containing the count of lowercase letters, uppercase letters, and total alphabetic characters.
13+
14+
Raises:
15+
FileNotFoundError: If the specified file does not exist.
16+
PermissionError: If the file cannot be accessed.
17+
"""
18+
try:
19+
with open(file_path, 'r', encoding='utf-8') as file:
20+
content = file.read()
21+
Counter(content)
22+
23+
lowercase_count = sum(1 for char in content if char.islower())
24+
uppercase_count = sum(1 for char in content if char.isupper())
25+
total_letters = lowercase_count + uppercase_count
26+
27+
return lowercase_count, uppercase_count, total_letters
28+
except FileNotFoundError:
29+
raise FileNotFoundError(f"File '{file_path}' not found.")
30+
except PermissionError:
31+
raise PermissionError(f"Permission denied to read '{file_path}'.")
32+
33+
def main() -> None:
34+
"""Main function to execute the character counting and display results."""
35+
try:
36+
file_path = Path("happy.txt")
37+
lowercase, uppercase, total = count_lowercase_chars(file_path)
38+
39+
print(f"The total number of lowercase letters is: {lowercase}")
40+
print(f"The total number of uppercase letters is: {uppercase}")
41+
print(f"The total number of alphabetic characters is: {total}")
1042

11-
print(f"The total number of lower case letters are {word_counter.get_total_lower()}")
12-
print(f"The total number of upper case letters are {word_counter.get_total_upper()}")
13-
print(f"The total number of letters are {word_counter.get_total()}")
43+
except (FileNotFoundError, PermissionError) as e:
44+
print(f"Error: {e}")
45+
except Exception as e:
46+
print(f"An unexpected error occurred: {e}")
1447

1548
if __name__ == "__main__":
16-
lowercase()
49+
main()
Lines changed: 57 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,67 @@
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"\nError: {e}. Please check the file path.")
59+
except IsADirectoryError as e:
60+
print(f"\nError: {e}")
61+
except PermissionError:
62+
print(f"\nError: No permission to access {file_path}")
63+
except Exception as e:
64+
print(f"\nUnexpected error: {e}")
4165

4266
if __name__ == "__main__":
43-
44-
write_to_file(file_name)
45-
time.sleep(1)
46-
check_first_letter()
67+
main()
Lines changed: 68 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,68 @@
1-
with open("happy.txt", "r") as F:
2-
# method 1
3-
for i in F.read().split():
4-
print(i, "*", end="")
5-
print("\n")
6-
7-
# method 2
8-
F.seek(0)
9-
for line in F.readlines():
10-
for word in line.split():
11-
print(word, "*", end="")
1+
from pathlib import Path
2+
from typing import Optional
3+
4+
def print_words_with_asterisk(file_path: Optional[str | Path] = None) -> None:
5+
"""
6+
Reads a text file and prints each word followed by an asterisk (*) using two methods.
7+
Handles file paths with spaces and subdirectories.
8+
9+
Args:
10+
file_path (str | Path, optional): Path to the text file.
11+
Defaults to "1 File handle/File handle text/happy.txt" if not specified.
12+
13+
Raises:
14+
FileNotFoundError: If the file does not exist at the specified path.
15+
IsADirectoryError: If the path points to a directory instead of a file.
16+
PermissionError: If read access to the file is denied.
17+
"""
18+
# Set default path if not provided (handles spaces and subdirectories)
19+
if file_path is None:
20+
file_path = Path("1 File handle/File handle text/happy.txt")
21+
else:
22+
file_path = Path(file_path) # Convert to Path object for consistent handling
23+
24+
# Validate the file path
25+
if not file_path.exists():
26+
raise FileNotFoundError(f"File does not exist: {file_path.resolve()}")
27+
if not file_path.is_file():
28+
raise IsADirectoryError(f"Path is a directory, not a file: {file_path.resolve()}")
29+
30+
try:
31+
with open(file_path, 'r', encoding='utf-8') as file:
32+
print(f"Processing file: {file_path.resolve()}\n") # Show absolute path for verification
33+
34+
# Method 1: Split entire file content into words
35+
content = file.read()
36+
words = content.split()
37+
38+
print("Method 1 Output:")
39+
for word in words:
40+
print(f"{word}*", end="")
41+
print("\n") # Newline after method 1 output
42+
43+
# Reset file pointer to start for method 2
44+
file.seek(0)
45+
46+
# Method 2: Process line by line, then split lines into words
47+
print("Method 2 Output:")
48+
for line in file:
49+
line_words = line.split()
50+
for word in line_words:
51+
print(f"{word}*", end="")
52+
print() # Final newline after all output
53+
54+
except PermissionError:
55+
raise PermissionError(f"Permission denied: Cannot read {file_path.resolve()}")
56+
57+
if __name__ == "__main__":
58+
try:
59+
# You can explicitly pass the path if needed, e.g.:
60+
# custom_path = r"C:\Full\Path\To\1 File handle\File handle text\happy.txt" # Windows
61+
# print_words_with_asterisk(custom_path)
62+
63+
# Use default path (works for relative paths)
64+
print_words_with_asterisk()
65+
except (FileNotFoundError, IsADirectoryError, PermissionError) as e:
66+
print(f"Error: {e}")
67+
except Exception as e:
68+
print(f"Unexpected error: {e}")

0 commit comments

Comments
 (0)