Python Tutorial Python Advanced Python Resources Python Libraries
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Python - File writelines() Method



The Python file writelines() method is used to write the string elements of an iterable to the file.

Syntax

file.writelines(iterable)

Parameters

iterable Required. iterable with string items.

Return Value

None.

Write to an Existing File

To write content in the existing file, the following file open() modes can be used.

  • "a" - append mode. to append to the end of the file.
  • "w" - write mode. to overwrite any existing content of the file.

The below code can be used to write content in a given file in append and write mode respectively.

#append content to the file 
MyFile = open("test.txt", "a")
#list iterable is used here
MyFile.writelines(["Add more content.", 
                   "Add this content also."])
MyFile.close()

#overwrite existing content of the file 
MyFile = open("test.txt", "w")
#tuple iterable is used here
MyFile.writelines(("Overwrite content.", 
                   "With this content."))
MyFile.close()

Write to a new File

To create a new file, the file open() function can be used in following modes:

  • "a" - append mode. Opens a file in append mode and creates the file if it does not exist.
  • "w" - write mode. Opens a file in write mode and creates the file if it does not exist.
  • "x" - create mode. Creates a file and raises exception if it already exists.

The below code can be used to create a new file called test.txt (if the file does not exit) using append, write and create mode respectively.

#Creates a file "test.txt" if it does not exist 
MyFile = open("test.txt", "a")
MyFile.writelines(["Add more content.", 
                   "Add this content also."])
MyFile.close()

#Creates a file "test.txt" if it does not exist 
MyFile = open("test.txt", "w")
MyFile.writelines(["Add more content.", 
                   "Add this content also."])
MyFile.close()

#Creates a new file "test.txt" and raises
#exception if it already exists
MyFile = open("test.txt", "x")
MyFile.writelines(["Add more content.", 
                   "Add this content also."])
MyFile.close()

Example:

In the example below, the file writelines() method is used to write content of an iterable to a new file.

#file is opened in write mode
MyFile = open("test.txt", "w")
MyFile.writelines(["This is line 1 content.\n", 
                   "This is line 2 content.\n", 
                   "This is line 3 content."])
MyFile.close()

#read the file
MyFile = open("test.txt", "r")
for line in MyFile:
  print(line, end="")
MyFile.close()

The output of the above code will be:

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

❮ Python File Handling Methods

5