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

COMPUTER SOFTWARE APPLICATION - CITS




           2  File Write:
           •  fileptr.write(“Hello, this is a sample line.\n”): Writes the first line to the file.
           •  fileptr.write(“Writing another line to the file.\n”): Writes the second line to the file.
           •  The “\n” is used to add a newline character at the end of each line.
           3  print(“Content has been written to the file.”):

           •  This line is not necessary for file writing but serves as a confirmation message that the content has been
              written.
              After running this code, you should find a file named “file.txt” in the same directory with the specified lines
              written to it.
           Output;









           To see the content of the file named file.txt use the following command  in the Command Prompt/Terminal.
           F:\Python> Type file.txt
           You will get the output like this












           TASK 3 : Python program that demonstrates file manipulation, including reading, writing, and appending
                    to a file
           Code:
           # Step 1: Open a file for writing

           with open(“sample_file.txt”, “w”) as fileptr:
           # Step 2: Write content to the file
           fileptr.write(“Hello, this is a sample line.\n”)
           fileptr.write(“Writing another line to the file.\n”)

           # Step 3: Open the same file for reading
           with open(“sample_file.txt”, “r”) as fileptr:
           # Step 4: Read and print the file content
           file_content = fileptr.read()
           print(“File Content (Read Mode):\n”, file_content)

           # Step 5: Open the same file for appending
           with open(“sample_file.txt”, “a”) as fileptr:
           # Step 6: Append more content to the file
           fileptr.write(“Appending a new line to the file.\n”)

           # Step 7: Open the file again for reading



                                                           288

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