Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
126 views
in Python by (176k points)
Python File writelines() Method

Please log in or register to answer this question.

1 Answer

0 votes
by (176k points)

The writelines() method in Python is used to write a list of strings to a file. It takes an iterable of strings as input and writes each string to the file.

Here's the syntax of the writelines() method:

file.writelines(iterable)
 

Here, file is the file object that has been opened using the open() method, and iterable is an iterable object containing strings to be written to the file.

Let's take an example:

lines = ['This is the first line.\n', 'This is the second line.\n', 'This is the third line.\n']

file = open("example.txt", "w")
file.writelines(lines)
file.close()
 

In this example, we're creating a list of strings called lines, where each string represents a line of text to be written to the file. We're then opening a file called example.txt in write mode using the open() method. We're then writing the list of strings to the file using the writelines() method and closing the file using the close() method.

After running the above code, if you open the example.txt file, you will see the following contents:

This is the first line.
This is the second line.
This is the third line.
 

Note that the writelines() method does not add newline characters between the strings, so you need to add them manually as we did in the lines list in the above example. Also, always remember to close the file using the close() method after writing to it.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Apr 4, 2023 in Python by kvdevika (176k points)
0 votes
1 answer
asked Apr 4, 2023 in Python by kvdevika (176k points)
0 votes
1 answer
asked Apr 4, 2023 in Python by kvdevika (176k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...