Open In App

Difference between write() and writelines() function in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In Python, there are many functions for reading and writing files. Both reading and writing functions work on open files (files opened and linked via a file object). In this section, we are going to discuss the write functions to manipulate our data through files.

write() function

The write() function will write the content in the file without adding any extra characters.

Syntax

# Writes string content referenced by file object.
file_name.write(content) 

As per the syntax, the string that is passed to the write() function is written into the opened file. The string may include numbers, special characters, or symbols. While writing data to a file, we must know that the write function does not add a newline character(\n) to the end of the string. The write() function returns None.

Example: 

Python3




file = open("Employees.txt", "w")
  
for i in range(3):
   name = input("Enter the name of the employee: ")
   file.write(name)
   file.write("\n")
     
file.close()
  
print("Data is written into the file.")


Output:

Data is written into the file.

Sample Run:

Enter the name of the employee: Aditya
Enter the name of the employee: Aditi
Enter the name of the employee: Anil

writelines() function

This function writes the content of a list to a file.

Syntax:   

# write all the strings present in the list "list_of_lines" 
# referenced by file object.
file_name.writelines(list_of_lines)

As per the syntax, the list of strings that is passed to the writelines() function is written into the opened file. Similar to the write() function, the writelines() function does not add a newline character(\n) to the end of the string.

Example:

Python3




file1 = open("Employees.txt", "w")
lst = []
for i in range(3):
    name = input("Enter the name of the employee: ")
    lst.append(name + '\n')
      
file1.writelines(lst)
file1.close()
print("Data is written into the file."


Output:

Data is written into the file.

Sample Run:

Enter the name of the employee: Rhea
Enter the name of the employee: Rohan
Enter the name of the employee: Rahul

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



Last Updated : 22 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads