Computer Science – 20.2 File Processing and Exception Handling | e-Consult
20.2 File Processing and Exception Handling (1 questions)
Model Answer 1
This solution demonstrates how to read a file, process the content (counting words), and write the results to another file. It includes error handling for file existence.
import re
def processfile(inputfilename, output_filename):
try:
with open(input_filename, 'r', encoding='utf-8') as infile:
text = infile.read()
except FileNotFoundError:
print(f"Error: File '{input_filename}' not found.")
return
words = re.findall(r'\b\w+\b', text.lower()) # Extract words, convert to lowercase
word_counts = {}
for word in words:
wordcounts[word] = wordcounts.get(word, 0) + 1
try:
with open(output_filename, 'w', encoding='utf-8') as outfile:
for word, count in word_counts.items():
outfile.write(f"{word}: {count}\n")
except Exception as e:
print(f"Error writing to file '{output_filename}': {e}")
if name == "main":
input_file = "data.txt"
outputfile = "wordcounts.txt"
processfile(inputfile, output_file)
Explanation:
- The code first attempts to open the input file. If the file is not found, it prints an error message and exits.
- It reads the entire content of the file into a string.
- The
re.findall()function is used with a regular expression to extract all words from the text, converting them to lowercase for case-insensitive counting. - A dictionary
word_countsis used to store the count of each word. - The code then iterates through the
word_countsdictionary and writes each word and its count to the output file. - Error handling is included for potential issues during file writing.