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.