Write Multiple Lines to a File using a Context Manager in Python

To write multiple lines to a file in Python using a context manager, we use the with statement along with the built-in open() function. The with statement ensures that the file is properly closed after writing, even if an error occurs. We can use the write() or writelines() method to write multiple lines efficiently.


Examples for Writing Multiple Lines to a File

1. Writing Multiple Lines Using a List and writelines()

In this example, we will create a text file and write multiple lines using the writelines() method. This method takes a list of strings and writes them to the file in one go.

main.py

</>
Copy
# Define a list of lines to write
lines = ["apple\n", "banana\n", "cherry\n"]

# Using a context manager to write to a file
with open("example1.txt", "w") as file:
    file.writelines(lines)

Explanation:

  1. lines: A list containing multiple string lines, each ending with a newline character (\n).
  2. open("example1.txt", "w"): Opens the file in write mode ("w"). If the file exists, it is overwritten; otherwise, a new file is created.
  3. with statement: Ensures the file is closed automatically after writing.
  4. file.writelines(lines): Writes the entire list of lines to the file without adding extra newline characters.

Output (Content of example1.txt):

2. Writing Multiple Lines Using a Loop and write()

In this example, we will use a loop to write each line separately using the write() method.

main.py

</>
Copy
# Define a list of lines to write
lines = ["This is line 1.\n", "This is line 2.\n", "This is line 3.\n"]

# Using a context manager and a loop to write to a file
with open("example2.txt", "w") as file:
    for line in lines:
        file.write(line)

Explanation:

  1. lines: A list containing multiple lines to be written.
  2. open("example2.txt", "w"): Opens the file in write mode.
  3. with statement: Ensures the file is closed automatically.
  4. for line in lines: Iterates over the list. Reference: For loop
  5. file.write(line): Writes each line separately to the file.

Output (Content of example2.txt):

3. Writing Multiple Lines Using a Loop and Formatted Strings

Here, we will use formatted strings inside a loop to dynamically write data to a file.

main.py

</>
Copy
# Define a list of items
items = ["Apples", "Bananas", "Cherries"]

# Using a context manager and formatted strings
with open("example3.txt", "w") as file:
    for i, item in enumerate(items, start=1):
        file.write(f"{i}. {item}\n")

Explanation:

  1. items: A list of fruit names.
  2. open("example3.txt", "w"): Opens the file in write mode.
  3. for i, item in enumerate(items, start=1): Loops over the list with an index starting from 1. Reference: For loop, enumerate()
  4. file.write(f"{i}. {item}\n"): Writes formatted lines (e.g., “1. Apples”).

Output (Content of example3.txt):

Conclusion

Writing multiple lines to a file in Python using a context manager is simple and efficient. In this tutorial, we covered the following methods:

  1. Using writelines(): Best for writing a list of lines at once.
  2. Using write() in a loop: Adds more control over individual line writing.
  3. Using formatted strings: Allows writing structured and indexed content dynamically.

The with statement ensures the file is always properly closed, preventing resource leaks.