The writelines() method in Python is a powerful tool for efficiently writing multiple lines of text to a file. It allows you to write a list of strings directly to a file, making it a convenient choice when dealing with data stored in lists. Let's delve into its functionalities, syntax, and practical applications.

Function Syntax

file_object.writelines(lines)
  • file_object: A file object that has been opened in write ('w') or append ('a') mode.
  • lines: An iterable object (usually a list) containing strings to be written to the file. Each element in the iterable will be written to the file as a separate line.

Functionality

The writelines() method iterates through the provided iterable, writing each string in the iterable to the file. It appends the string to the end of the file if the file was opened in append mode ('a') and overwrites the existing content if opened in write mode ('w').

Return Value

The writelines() method doesn't explicitly return any value.

Example 1: Writing a List of Strings to a File

# Create a list of strings
lines = ["This is line 1.\n", "This is line 2.\n", "This is line 3.\n"]

# Open a file in write mode
with open("output.txt", "w") as file:
    # Write the list of strings to the file
    file.writelines(lines)

# Display the content of the output file
with open("output.txt", "r") as file:
    content = file.read()
    print(content)

Output:

This is line 1.
This is line 2.
This is line 3.

In this example, we created a list called lines containing three strings. Then, we opened a file named "output.txt" in write mode ("w") using the with statement, which ensures the file is automatically closed when the code block is finished. We then used file.writelines(lines) to write the strings from the lines list to the file.

Example 2: Appending to an Existing File

# Create a list of strings
new_lines = ["This is a new line 1.\n", "This is a new line 2.\n"]

# Open a file in append mode
with open("output.txt", "a") as file:
    # Append the new lines to the file
    file.writelines(new_lines)

# Display the content of the output file
with open("output.txt", "r") as file:
    content = file.read()
    print(content)

Output:

This is line 1.
This is line 2.
This is line 3.
This is a new line 1.
This is a new line 2.

Here, we append two new lines to the "output.txt" file. Opening the file in append mode ("a") ensures that the new lines are added at the end of the existing content without overwriting it.

Example 3: Writing a List of Numbers to a File

# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Open a file in write mode
with open("numbers.txt", "w") as file:
    # Convert numbers to strings and write them to the file
    file.writelines([str(number) + "\n" for number in numbers])

# Display the content of the output file
with open("numbers.txt", "r") as file:
    content = file.read()
    print(content)

Output:

1
2
3
4
5

In this example, we demonstrate writing a list of numbers to a file. We iterate through the numbers list and convert each number to a string before appending a newline character. This process allows us to write each number on a separate line in the file.

Common Mistakes

  • Forgetting to open the file in write or append mode: If you open the file in read mode ('r'), the writelines() method will throw an error because the file is not opened for writing.

  • Not adding newlines: Without newlines, the strings will be written to the file consecutively without line breaks, making it difficult to read the content.

  • Using the wrong iterable: The writelines() method expects an iterable object (like a list, tuple, or set) containing strings. Passing a single string will result in an error.

Performance Considerations

The writelines() method is optimized for writing multiple lines to a file, making it more efficient than repeatedly calling the write() method for each line. This optimization becomes noticeable when working with large datasets.

Summary

The writelines() method is a valuable tool for efficiently writing multiple lines of text to a file in Python. Its ability to handle iterables of strings makes it ideal for processing data stored in lists, tuples, or other iterable objects. By understanding its syntax and capabilities, you can effectively manage file writing tasks and improve the efficiency of your Python programs.