Python method called write_multiple_lines
that writes multiple lines of text content into a text file named “mylife.txt”:
def write_multiple_lines(contents): try: with open("mylife.txt", 'w') as file: file.writelines(contents) print("Text content written successfully to 'mylife.txt'.") except IOError: print("Error occurred while writing to file.") # Example usage: text_contents = ["This is line 1.\n", "This is line 2.\n", "This is line 3.\n"] write_multiple_lines(text_contents)
In the write_multiple_lines
method, the contents
parameter is a list of strings representing the lines of text you want to write to the file. Each string should include the line content followed by the newline character (\n
) to separate the lines.
The method opens the file “mylife.txt” in write mode ('w'
) and uses the writelines
method to write the list of contents into the file. Each element of the list is written as a separate line.
After writing the contents, the method prints a success message.