CBSE Class 12 Computer Science Question 114 of 145

File Handling — Question 10

Back to all questions
10
Question

Question 10

Write a method in Python to write multiple line of text contents into a text file mylife.txt.line.

Answer
def write_to_file(file_path):
    lines_to_write = ["The sun sets over the horizon.", "Birds chirp in the morning.", "Raindrops patter on the roof.", "Leaves rustle in the breeze."]
    with open(file_path, "w") as file:
        for line in lines_to_write:
            file.write(line + '\n')  

write_to_file("mylife.txt.line")