File Operations and Word Count Program in Python
File Operations and Word Count Program in Python
operation:
readline(): Reads one line at a time.
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.")