Skip to main content

writelines()

The writelines() function is a method of the file object in Python that is used to write a list of lines to a file. It takes a list of strings as input and writes each string in the list to the file without adding any line separators. This function does not add a newline character at the end of each line, so it is useful when you want to write multiple lines to a file without any additional formatting.

Parameter Values

Parameter Description
lines

An iterable of strings to be written to the file. Each string represents a line in the file.

Return Values

The writelines() method in Python does not return any value; it returns None.

How to Use writelines() in Python

Example 1:

The writelines() method writes a list of lines to a file. It does not add line separators like \n.

lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('example.txt', 'w') as file:
    file.writelines(lines)
Example 2:

If the list contains strings without line separators, they will be written as single lines.

lines = ['Line 1', 'Line 2', 'Line 3']
with open('example.txt', 'w') as file:
    file.writelines(lines)
Example 3:

It is recommended to include line separators in the list elements to ensure proper line breaks.

lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('example.txt', 'w') as file:
    file.writelines(lines)