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

COMPUTER SOFTWARE APPLICATION - CITS




           with open(“sample_file.txt”, “r”) as fileptr:
           # Step 8: Read and print the updated file content
           updated_content = fileptr.read()
           print(“\nUpdated File Content (Read Mode):\n”, updated_content)

           Explanation:
           1  Opening File for Writing (“w”):
           •  with open(“sample_file.txt”, “w”) as fileptr: opens the file “sample_file.txt” in write mode.
           •  write method is used to write content to the file.
           2  Reading File Content (“r”):

           •  with open(“sample_file.txt”, “r”) as fileptr: opens the file in read mode to read its content.
           •  read method is used to read and print the file content.
           3  Appending to the File (“a”):
           •  with open(“sample_file.txt”, “a”) as fileptr: opens the file in append mode.
           •  write method is used to append content to the file.

           4  Reading Updated File Content (“r”):
           •  with open(“sample_file.txt”, “r”) as fileptr: opens the file again in read mode.
           •  read method is used to read and print the updated file content.
              After running this code, you should see the content of “sample_file.txt” displayed, including the appended line.

           Output:




















           Related Exercises:
           1  File Reading:
              •  Write a Python program to read the contents of a file and display them.
              •  Modify the program to read only the first N lines of the file.

           2  File Writing:
              •  Create a Python program to write a list of strings to a file.
              •  Allow the user to input multiple lines of text and save them to a file.
           3  Appending to a File:

              •  Write a program to append new data to an existing file.
              •  Allow the user to input additional lines and append them to the file.





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