CBSE Class 12 Computer Science Question 95 of 136

Data File Handling — Question 34

Back to all questions
34
Question

Question 34

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

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")