Experiment -7
Title: Program to write a file using writelines() method.
In order to write data into a file, we must open the file in write mode.
We need to be very careful while writing data into the file as it overwrites the content
present inside the file that you are writing, and all the previous data will be erased.
We have two methods for writing data into a file as shown below.
[Link](string)
[Link](list)
Writelines()
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.
If the current file 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
file_handler.writelines(list_of_strings)
Example:
# Writelines function
first_string = "Hello"
second_string = "World!"
third_string = "I am "
fourth_string = "learning"
fifth_string = "Python"
full_string = [first_string, second_string, third_string, fourth_string, fifth_string]
new_file = open("[Link]", 'w')
new_file.writelines(full_string)
new_file.close()
Output:
HelloWorld!I am learningPython
Conclusion:
Thus, in this experiment we have studied to write a file using writelines() method in
python successfully.