[Type B] File Handling – Chapter 5 Sumita Arora

|
Table of Contents

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

Answer: Here’s a method to write multiple lines of text into a text file in Python:

Python
def write_to_file(file_name, lines):
    with open(file_name, 'w') as file:
        for line in lines:
            file.write(line + '\n')

# Example usage
lines_to_write = ["This is the first line.", "This is the second line.", "And so on..."]
write_to_file('mylife.txt', lines_to_write)

Code Explanation:

  • Function Definition: The write_to_file function takes two parameters: file_name and lines. The file_name parameter is the name of the text file to write to, and the lines parameter is a list of strings to write as separate lines in the file.
  • File Opening: The function uses a with statement to open the file in write mode (‘w’). Inside the with block, a loop is used to iterate over each line in the lines list.
  • Writing Lines: The file.write() method is used to write each line to the file, followed by a newline character (‘\n‘) to create a new line for the next line.
    • Finally, the write_to_file function is called with the name of the text file to write to (‘mylife.txt’) and a list of lines to write to the file.
  • After running this code, a file named ‘mylife.txt’ will be created in the same directory as the Python script, with the specified lines of text written to it.
Python
def write_to_file(file_name, lines):
  try:
    with open(file_name, 'w') as file:
      for line in lines:
        file.write(line + '\n')  
  except Exception as e:
    print(f"Error writing to file: {e}")

# Example usage
lines_to_write = ["This is the first line.", "This is the second line.", "And so on..."]
write_to_file("mylife.txt", lines_to_write)

Code Explanation:

  • Function Definition: The code defines a function write_to_file that takes a filename and a list of lines as inputs.
  • Error Handling: Includes a try-except block for handling potential exceptions during file operations.
  • File Opening: Opens the file in write mode ("w") using the with statement.
  • Writing Lines: Iterates through the list of lines and writes each line to the file, adding a newline ("\n").
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *

One Comment