Page 302 - CTS - CSA TP - Volume 2
P. 302

COMPUTER SOFTWARE APPLICATION - CITS




           TASK 1: Program code for read mode
              It is a read operation in Python. We open an existing file with the given code and then read it. The code
              is given below –
              # Open the file in read mode
              with open(“file.txt”, “r”) as fileptr:
               # Read the contents of the file
               file_content = fileptr.read()

               # Print the content
               print(file_content)
           Explanation:
           with open(“file.txt”, “r”) as fileptr:

           •  with: The with statement is used to wrap the execution of a block with methods defined by a context manager.
              It ensures that the file is properly closed after the block execution, even if an exception occurs.
           •  open(“file.txt”, “r”): The open function is used to open a file. The first argument is the filename (“file.txt” in this
              case), and the second argument is the mode (“r” for read mode).
           •  as fileptr: It assigns the file object returned by open to the variable fileptr. This variable is used to interact with
              the file.

           file_content = fileptr.read():
           •  fileptr.read(): The read method is called on the file object (fileptr). It reads the entire content of the file and
              returns it as a string, which is then assigned to the variable file_content.
           print(file_content):

           •  print(file_content): This line prints the contents of the file, which were stored in the file_content variable.
           •  The use of the with statement is good practice because it automatically takes care of closing the file when the
              indented block is exited, ensuring proper resource management.

           Output:










           TASK 2: Open the file in write mode
           # Open the file in write mode
           with open(“file.txt”, “w”) as fileptr:
           # Write content to the file
           fileptr.write(“Hello, this is a sample line.\n”)

           fileptr.write(“Writing another line to the file.\n”)
           print(“Content has been written to the file.”)
           Explanation:
           1  with open(“file.txt”, “w”) as fileptr::
           •  This line opens the file named “file.txt” in write mode (“w”).

           •  The with statement ensures that the file is properly closed after writing.




                                                           287

                              CITS : IT & ITES - Computer Software Application - Exercise 133
   297   298   299   300   301   302   303   304   305   306   307