[Type C]Q4. Write a program to count the words “to” and “the” present in a text file “Poem.text”

What is file handling?

Python has several functions for creating, reading, updating, and deleting files.

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" – Read – Default value. Opens a file for reading, error if the file does not exist

"a" – Append – Opens a file for appending, creates the file if it does not exist

"w" – Write – Opens a file for writing, creates the file if it does not exist

"x" – Create – Creates the specified file, returns an error if the file exists

The close() command terminates all the resources in use and frees the system of this particular program.

Program code:

Output:

3 
25

File Handling in python is demonstrated in above program.

To view all the lessons in chapter 1: http://computertutor.in/class-12-computer-science/chapter-5/

To view entire class 12 computer science study material: http://computertutor.in/resources/

You cannot copy content of this page