Page 301 - CTS - CSA TP - Volume 2
P. 301
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 133 : Write a python program to read and write
into a file
Objectives
At the end of this exercise you shall be able to
• develop python programs to read and write into a file.
Procedure
In Python, file handling is an essential part of programming that allows you to work with files on your computer.
You can read from existing files, write to new files, and perform various operations on files. Here’s a brief overview
of Python file handling:
Opening a File: To open a file, you can use the built-in open() function. It takes two parameters – the file name
and the mode (read, write, or append).
Common modes:
• “r”: Read (default mode).
• “w”: Write (creates a new file or truncates an existing file).
• “a”: Append (opens a file for appending new content).
Reading from a File: You can read the content of a file using various methods such as read(), readline(), or
readlines().
Writing to a File: To write content to a file, open the file in write mode (“w”) or append mode (“a”) and use the
write() method.
Closing a File: It’s important to close the file after you’re done with it. The with statement automatically closes
the file when the block is exited.
286