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
137 views
in Python by (176k points)
Python File readlines() Method

Please log in or register to answer this question.

1 Answer

0 votes
by (176k points)

The readlines() method in Python is used to read all the lines of a file and return them as a list of strings. Each line is represented as a string in the list, and the newline character at the end of each line is also included in the string.

Here is the syntax of the readlines() method:

file_object.readlines()
 

Here, file_object is the name of the file object on which the readlines() method is called.

Let's see an example to understand how the readlines() method works:

Suppose we have a text file named "example.txt" with the following contents:

This is the first line.
This is the second line.
This is the third line.
 
# Open the file for reading
file = open("example.txt", "r")

# Read all the lines from the file
lines = file.readlines()

# Close the file
file.close()

# Print the lines
print(lines)
 

Output:

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

In the above example, we open the file "example.txt" in read mode and read all the lines from the file using the readlines() method. The lines are returned as a list of strings, with each line as a separate string in the list. Finally, we close the file and print the lines using the print() statement.

Note that the newline character (\n) at the end of each line is also included in the string. We can remove the newline character using the strip() method, as shown below:

# Open the file for reading
file = open("example.txt", "r")

# Read all the lines from the file and remove newline character
lines = [line.strip() for line in file.readlines()]

# Close the file
file.close()

# Print the lines
print(lines)
 

Output:

['This is the first line.', 'This is the second line.', 'This is the third line.']
 

In the above example, we use a list comprehension to remove the newline character from each line and create a new list with the modified lines.

Related questions

0 votes
1 answer
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

...