Practical 3: program to create and write multiple lines into a file using the writelines() method.
Problem Statement
Write a Python program to create and write multiple lines into a file using the writelines() method.
Solution Code
# Program to write multiple lines to a file using writelines()
# Open the file in write mode
file = open("output.txt", "w")
# List of lines to write into the file
lines = ["Hello, this is line 1.\n",
"This is line 2.\n",
"Writing to a file using writelines().\n"]
# Write the list of lines into the file
file.writelines(lines)
# Close the file
file.close()
print("Data written to output.txt successfully.")
Expected Outcome
- The program creates a file named output.txt (or overwrites it if it already exists).
- The given lines are written into the file.
- The output file should contain:
Data written to output.txt successfully.
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 4 Practical 3 solution where we have written Python program to create and write multiple lines into a file using the writelines() method.
- Opening the File in Write Mode
- The open(“output.txt”, “w”) function opens the file in write mode, meaning if the file already exists, it will be overwritten.
- Writing Multiple Lines Using writelines()
- A list of strings is created, where each string represents a line to be written.
- The writelines() method writes all the lines to the file at once.
- Unlike write(), writelines() does not automatically insert newline characters, so we include \n at the end of each line.
- Closing the File
- The file.close() method ensures that the file is properly saved and resources are freed.
- Displaying a Success Message
- The program prints a confirmation message after writing to the file.
Key Concepts Learned
- File Handling in Python
- Using open(“filename”, “w”) to create and write to a file.
- Understanding that w mode overwrites existing content.
- Using writelines() for Writing Multiple Lines
- writelines() writes a sequence of strings efficiently.
- The importance of including \n manually when writing multiple lines.
- Closing Files
- Ensuring the file is closed after writing to prevent data corruption.