Python file writelines() method

Python File writelines() Method

The writelines() method writes a sequence of strings to a file. The sequence can be any iterable object, typically a list of strings. This method has no return value.

Syntax

The syntax of the writelines() method is as follows:

fileObject.writelines(sequence)

Parameters

  • sequence – This is the sequence of strings.

Return Value

This method does not return any value.

The following example shows the usage of the writelines() method.

Suppose the file ‘foo.txt’ contains the following text –

This is 1st line
This is 2nd line
This is 3rd line
This is the 4th line
This is the 5th line

Example

# Open a file in read/write mode
fo=open("foo.txt","r+")
seq = ["This is 6th linen", "This is 7th line"]

# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines(seq)
fo.seek(0,0)
while True:
   try:
      line=next(fo)
      print(line)
   except:
      StopIteration break
fo.close()

When we run the above program, it will produce the following output –

Name of the file: foo.txt
Line No. 0 - This is the 1st line
Line No. 1 - This is the 2nd line
Line No. 2 - This is the 3rd line
Line No. 3 - This is the 4th line
Line No. 4 - This is the 5th line
Line No. 5 - This is the 6th line
Line No. 6 - This is the 7th line

Leave a Reply

Your email address will not be published. Required fields are marked *