Have you ever wanted to read a file line by line in Python? Then you should be familiar with the Python `readlines()`
Method! This powerful Python Method is used to read a file line by line and store each line in a list. This means you can access each line of the file using a simple list index, and you can easily manipulate the contents of the file.
The `readlines()`
Method is very useful for reading files that contain lots of information or have many lines of text. You can also use the `readlines()`
Method to read a file one line at a time, which is great for file-processing tasks. What’s even better is that the `readlines()`
Method is easy to use and can be implemented in just a few lines of code. So if you’re looking for a reliable way to read files in Python, look no further than the `readlines()`
Method!
Syntax:
The `readlines()`
method uses the following syntax:
1 | file_object.readlines() |
The `readlines()`
method reads all the lines of the file and returns them as a list of strings, with each string representing a line in the file. The newline character at the end of each line is included in the string.
Example:
Let’s understand the Python’s `readlines()`
method with a few examples. Consider the following file myfile.txt:
cat myfile.txt
Apple
Banana
Mango
Orange
Pineapple
To read all the lines of this file using the `readlines()`
method, you can do the following:
1 2 3 4 5 6 7 | # Open the file in read mode with open('myfile.txt', 'r') as f: # Read all the lines of the file lines = f.readlines() # Print the list of lines print(lines) |
This will print the following output:
Output:['Apple\n', 'Banana\n', 'Mango\n', 'Orange\n', 'Pineapple\n']
As you can see, the `readlines()`
method returns a list of strings, with each string representing a line in the file and the newline character at the end of each line included in the string.
You can also use the `readlines()`
method to read a specific number of bytes from the file, as shown in the following example:
1 2 3 4 5 6 7 | # Open the file in read mode with open('myfile.txt', 'r') as f: # Limit number of bytes to return lines = f.readlines(14) # Print the list of lines print(lines) |
This will print the following output:
Output:['Apple\n', 'Banana\n', 'Mango\n']
As you can see, the `readlines()`
method reads the specified number of byes from the file and returns them as a list of strings.
The `readlines()`
method is generally slower than using the for loop and the `readlines()`
method to read the lines of a file, as it reads all the lines of the file into memory at once. However, it is more convenient to use and can be useful when you want to read all the lines of a file in a single call.