Programming Examples

Write a program that opens a file named data.txt in write mode, and writes multiple lines to it from a list of strings.


Write a program that opens a file named data.txt in write mode, and writes multiple lines to it from a list of strings.

Solution

lines = [   "This is the first line.\n",    "This is the second line.\n",    "This is the third line.\n"]
fp=open("data.txt", "w")
fp.writelines(lines)
fp.close()
print("Data written to data.txt successfully.")
▶ RUN

Output/ Explanation:

Opens the file in write mode ("w").

Writes all strings from the list using writelines().

Latest Current Affairs 2026 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online MBA 2 years Online MCA Online BCA Best Website and Software Company in Allahabad