Practical 11: Program that reads a file and counts the number of tab (\t) space ( ) and newline (\n) characters present in the file.
Problem Statement
Write a Python program that reads a file and counts the number of tab (\t) space ( ) and newline (\n) characters present in the file.
Solution Code
# Function to count tabs, spaces, and newlines in a file
def count_whitespace(filename):
try:
with open(filename, "r") as file:
content = file.read()
# Counting occurrences of tab, space, and newline characters
tab_count = content.count("\t")
space_count = content.count(" ")
newline_count = content.count("\n")
# Display the counts
print(f"Tabs: {tab_count}")
print(f"Spaces: {space_count}")
print(f"Newlines: {newline_count}")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
# Example usage
filename = "sample.txt" # Change this to the actual file name
count_whitespace(filename)
Expected Outcome
The program should display the count of tabs, spaces, and newline characters present in the given file.
Example Output
Tabs: 0
Spaces: 10
Newlines: 1
Process finished with exit code
If the file does not exist, an error message will be displayed:
Error: The file 'sample.txt' was not found.
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 4 Practical 11 solution where we have written Python program that reads a file and counts the number of tab (\t) space ( ) and newline (\n) characters present in the file.
- Opening the File
- The program opens the file in read mode (“r”).
- Reading the File Content (file.read())
- The entire content of the file is stored in the content variable.
- Counting Special Characters
- content.count(“\t”) → Counts the number of tab characters.
- content.count(” “) → Counts the number of space characters.
- content.count(“\n”) → Counts the number of newline characters.
- Handling Missing Files (FileNotFoundError)
- If the file does not exist, an error message is displayed instead of crashing the program.
Key Concepts Learned
- File Handling (open(), read(), with statement)
- String Manipulation (count() function)
- Handling Exceptions (try-except for FileNotFoundError)