Python 3 – File readlines() Method
The readlines()
method in Python is used to read all the lines of a file and return them as a list of strings. This method can be used to read text files or any other files with multiple lines of data.
The readlines()
method can only be used with an open file, which can be achieved using the open() function. The open() function is used to open a file and returns a file object, which is used to perform operations on the file.
Here is an example of using the readlines()
method to read a text file:
# Opening a text file in read mode
file = open("sample.txt", "r")
# Reading all the lines of the file and storing them in a list
lines = file.readlines()
# Closing the file
file.close()
# Printing the list of lines
print(lines)
In the above example, we are opening a text file named “sample.txt” in read mode using the open()
function. Then we are calling the readlines()
method on the file object to read all the lines of the file and storing them in a list named lines
. Finally, we are closing the file using the close()
method and printing the list of lines using the print()
function.
If we want to print each line of the file separately, we can use a for loop to iterate over the list of lines:
# Opening a text file in read mode
file = open("sample.txt", "r")
# Reading all the lines of the file and storing them in a list
lines = file.readlines()
# Closing the file
file.close()
# Printing each line of the file separately
for line in lines:
print(line)
In the above example, we are opening a text file named “sample.txt” in read mode using the open()
function. Then we are calling the readlines()
method on the file object to read all the lines of the file and storing them in a list named lines
. Finally, we are closing the file using the close()
method and using a for loop to iterate over the list of lines
and printing each line using the print()
function.
We can also use the with
statement to open and close the file automatically:
# Using with statement to open and close the file automatically
with open("sample.txt", "r") as file:
lines = file.readlines()
# Printing the list of lines
print(lines)
In the above example, we are using the with
statement to open the file in read mode and automatically close it after the block of code executes. Then we are calling the readlines()
method on the file object to read all the lines of the file and storing them in a list named lines
. Finally, we are printing the list of lines using the print()
function.
Conclusion
In this article, we learned about the readlines()
method in Python and how to use it to read all the lines of a file and store them in a list of strings. We also learned how to open and close a file using the open()
function and the with
statement. The readlines()
method is a very useful method when working with files in Python and can save us a lot of time and effort.