"File Operations and Word
Count Program in Python":
Presented By : Sakshi Khandagale
Roll no-ET1-15
PRN-202401070066
Introduction 1
• File handling allows interaction with stored data—reading input
from files or writing output to them.
• Real-world programs often read from and write to external files
instead of relying solely on user input/output.
• A word count program is a simple demonstration of how to read
files, process text, and perform useful computation.
Types of File 2
Reading Data:
Opening a File: Operations
Use open(filename, mode) to open a read(): Reads entire file content as a
file. The mode defines the single string.
operation:
readline(): Reads one line at a time.
'r': Read mode (default) readlines(): Returns a list of lines.
'w': Write mode (overwrites file)
Writing Data:
'a': Append mode write(): Writes a string to the file.
'r+': Read and write mode writelines(): Writes a list of strings.
Python Code - File 3
Reading
file = open('sample.txt', 'r')
content = file.read()
print(content)
file.close()
Explanation:
Opens sample.txt in read mode.
Reads the entire file content.
Prints it to the console.
Closes the file after use.
PYTHON CODE - WORD COUNT
file = open('sample.txt', 'r')
text = file.read()
words = text.split()
word_count = len(words)
print("Total Words:", word_count)
file.close()
Explanation:
split() breaks text into words based on whitespace.
len(words) gives the total number of words.
This approach can be enhanced for more advanced NLP
tasks (e.g., removing punctuation).
Error Handling and Best
Always handle exceptions:
Practices
try:
with open('sample.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
Best Practice: Use with open(...) context manager—it automatically closes
the file, even if an error occurs.
Avoid hardcoding filenames; use variables or input prompts.
APPLICATIONS
• Text Analysis: Counting words, sentences, or
characters in documents.
• Log File Processing: Reading server logs to
monitor activity.
• Automation Scripts: Generate and update reports
automatically.
• NLP Preprocessing: Tokenizing and counting words
as a first step in machine learning.
Conclus
• Mastery of file operations ision
crucial
for handling real-world data.
• Word count is a beginner-friendly
task that introduces text processing
concepts.
• The skills learned here are
foundational for more complex
applications such as data parsing, file
conversions, and machine learning.
THANK YOU