Skip to content

Difference between write() and writelines in Python

  • by

The main difference between the write() and writelines() in Python is that write() is used to write a string to an already opened file while the writelines() method is used to write a list of strings in an opened file.

  • write() method takes a string as an argument and writes it to the text file.
  • writelines() method is used to write multiple strings to a file. We need to pass an iterable object like lists, tuples, etc. containing strings to the writelines() method.

Let’s say, you have a text file with already 10 Lines in it. Using .writelines() you would add them like so:

    seq = ["This is 11th line\n", "This is 12th line"]
    #Write sequence of lines at the end of the file.
    fo.seek(0, 2)
    line = fo.writelines( seq )

If you have the case, you simply would like to add 10 lines to a file, using file.write, you would implement it like so:

    for i in range(10):
        f.write("This is line %d\r\n" % (i+1))

Difference between write() and writelines in Python

A simple example code.

file = open("emp.txt", "w")

for i in range(3):
name = input("Enter the name of the employee: ")
file.write(name)
file.write("\n")

file.close()

Output:

Difference between write() and writelines in Python

The writelines() function does not add a newline character(\n) to the end of the string.

file1 = open("Employees.txt", "w")
lst = ['a', 'b', 'c']
for i in range(3):
file1.writelines(lst[i])

file1.close()

Output: abc

Do comment if you have any doubts or suggestions on this Python difference topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading