The readline() method in Python is used to read a single line from a file. It is helpful when working with large files, as it reads data line by line instead of loading the entire file into memory.
Syntax
file.readline(size)
Parameters
- size (Optional): The number of bytes from the line to return. Default -1, which means the whole line.
Return Value
Returns an empty string (''
) when the end of the file is reached.
Examples of readline()
First, let's create a file called example.txt with the following content:
This is the first line.
This is the second line.
This is the third line.
This is the fourth line.
1. Reading a Single Line
Python
with open("example.txt", "r") as file:
line = file.readline()
print(line) # Prints the first line of the file
Output:
This is the first line.
Explanation:
- file.readline() reads the first line from the file.
- It prints the first line, which is "This is the first line.", including the newline character (\n) at the end of the line.
2. Reading Multiple Lines with a Loop
Python
with open("example.txt", "r") as file:
while True:
line = file.readline()
if not line:
break # Stop when end of file is reached
print(line.strip())
Output:
This is the first line.
This is the second line.
This is the third line.
This is the fourth line.
Explanation:
- The while True: loop keeps reading lines until the end of the file is reached. file.readline() reads one line at a time.
- if not line: checks if the line is empty (which happens when the end of the file is reached). When it finds an empty line, it breaks out of the loop.
- line.strip() removes any trailing newline characters from the line before printing it.
3. Using readline() with a Specific Character Limit
Python
with open("example.txt", "r") as file:
line = file.readline(10)
print(line)
Output:
This is the
Explanation:
- file.readline(10) reads the first 10 characters of the first line in the file. It stops reading after the 10th character, regardless of whether it's at the end of the word or not.
- The print(line) statement will print exactly those 10 characters.
Difference Between readline(), readlines(), and read()
Method | Description |
---|
readline() | Reads one line at a time |
readlines() | Reads all lines and returns them as a list |
read() | Reads the entire file as a single string |