Python File writelines() Method



The Python File writelines() method writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.

When the method writes the sequence of strings into this file, it is first written into the internal buffer; and once this buffer is full, the contents are then transferred to the current file. Due to this buffering, the text may not actually show up in the file until the flush() or close() methods are called.

If the current is empty, the method adds content to it from the beginning; but if it already contains some text, the position at which this text is added into the file depends on the position of the file pointer; and this position varies based on the file modes. Various scenarios are as follows −

  • If the file is opened in the writing modes (w or w+), the existing text is erased from the file and the file pointer moves to the beginning of the file. Therefore, the writelines() method writes from the beginning in this case.
  • If the file is opened in the append modes (a or a+), the existing text remains as it is and the file pointer remains at the end of file. Hence, the new text is added after the existing contents.
  • If the file is opened in the read and write mode (r+), the pointer moves to the beginning of the file and replaces the existing content in the file. However, the entire text is not replaced; instead the writelines() method only replaces the characters in the existing strings with the characters of the new string objects. The remaining text in the file is left unchanged.
  • This method is not effective if the file is opened in the reading mode (r).

Syntax

Following is the syntax for the Python File writelines() method −

fileObject.writelines( sequence )

Parameters

  • sequence − This is the Sequence of the strings.

Return Value

This method does not return any value.

Example

Consider a demo file "foo.txt" containing strings.

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

The following example shows the usage of Python File writelines() method. The demo file is opened in the write (w) mode, so the existing content in the file will be erased and new content is inserted using this method. And since this method returns no values, the file must be directly checked to see the reflected changes.

# Open a file in write mode
fo = open("foo.txt", "w")
print("Name of the file: ", fo.name)

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

# Write a new line into the file
seq = ["This is the new line", '\n', "This is another new line"]
line = fo.writelines(seq)

print("Check the file to see the reflected changes")

# Close opened file
fo.close()

When we run above program, it produces following result −

Name of the file:  foo.txt
Check the file to see the reflected changes

Example

In the example above, one has to open the file to check whether the changes are reflected or not. But we can also try to display the file contents in the terminal itself. To do that, once the file is rewritten using the writelines() method, we close the file. Then, this file is opened again in the read (r) mode, and file contents are read using the read() method.

# Open a file in write mode
fo = open("foo.txt", "w")
print("Name of the file: ", fo.name)

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

# Write a new line
seq = ["This is the new line", '\n', "This is another new line"]
line = fo.writelines(seq)

# Close opened file
fo.close()

# Open the file again in read mode
fo = open("foo.txt", "r")

line = fo.read()
print("File Contents:", line)

# Close opened file again
fo.close()

On executing the program above, the output is displayed on the terminal as follows −

Name of the file:  foo.txt
File Contents: This is the new line
This is another new line

Example

If we try to open a file that does not exist in the directory with the write (w) mode, a new file is created with the given name. In the following example, writelines() method is called on this file and new contents are inserted into it.

# Open a non-existent file in write mode
fo = open("new.txt", "w")
print("Name of the file: ", fo.name)

# Write a new text
seq = ["Hello", '\n', "Welcome to Tutorialspoint"]
line = fo.writelines(seq)

print("Check the file to see the reflected changes")

# Close opened file
fo.close()

Let us compile and run the given program, the output is displayed as follows −

Name of the file:  new.txt
Check the file to see the reflected changes

Example

The writelines() method can also be used when the file is opened in the append (a or a+) mode.

In this example, a file named "foo.txt" is opened in the append mode "a". Since the file is opened in append mode, the writelines() method writes content at the end of file. With the write() method, the new line is appended immediately after the last character of the string; but with the writelines() method, as a newline character and a string are passed as objects to a list, the new string will be appended in the next line. The file contents are displayed in the terminal itself.

# Let the test file contain the following strings
# Hello!
# This is Tutorialspoint
# Welcome

# Open the test file in append mode
fo = open("test.txt", "a")
print("Name of the file: ", fo.name)

seq = ['\n', "This is the new line"]
fo.writelines(seq)

# Close opened file
fo.close()

# Open the file again in read mode
fo = open("test.txt", "r")

line = fo.read()
print("File Contents:", line)

# Close opened file again
fo.close()

Once the program is compiled and run, the output is displayed in the terminal as follows −

Name of the file:  test.txt
File Contents: Hello!
This is Tutorialspoint
Welcome
This is the new line

Example

If we use the writelines() method on a file opened using the read and write mode (r+), the pointer moves to the beginning of the file and replaces the existing content in the file.

In the example below, we are opening an existing file "foo.txt" in the "r+" mode. The existing characters in the file are replaced from the beginning by the characters in the string objects passed as a list. The remaining text in the file is left unchanged.

# Open the test file in append mode
fo = open("foo.txt", "r+")
print("Name of the file: ", fo.name)

seq = ["This is a new line", '\n', "This is another new line", '\n']
fo.writelines(seq)

print("Check the file to see the reflected changes")

# Close opened file again
fo.close()

# Open the file again in read mode
fo = open("foo.txt", "r")

line = fo.read()
print("File Contents:", line)

# Close opened file again
fo.close()

Let us compile and run the program above, to produce the result as follows −

Name of the file:  foo.txt
Check the file to see the reflected changes
File Contents: This is a new line
This is another new line
d line
This is 4th line
This is 5th line
python_file_methods.htm
Advertisements