Read contents of the file using readline() method in Python
In this tutorial, we are going to learn about how to Read contents of the file using readline() method in Python.
Readline()
The readline() method is used to read a line from the file.
Recommended to use this function for smaller sized files.
In this, we can also specify how many bytes from the line to return, by using the size parameter.
Syntax: file.readline(size)
In the above syntax, size refers to no of bytes from the line to return(parameter value).
Steps to read a line from file:
- Open the file.
- Read line.
- Process the line.
- Close the file.
Example:
f = open("codespeedydemo.txt", "r") print(f.readline())
Firstly we have to save a file with any name here we took codespeedydemo and saved with .txt format and we have to write something in that file so that if we read a line we get the content.
we get the first line as an output.
Output: Hello! Welcome to Codespeedy.
Example:
f = open("codespeedydemo.txt", "r") print(f.readline()) print(f.readline())
It will return both the first and second lines from the file.
Output: Hello! Welcome to Codespeedy. A good platform to learn.
Example:
f = open("codespeedydemo.txt", "r") print(f.readline(5))
In the above code, we have given parameter size as bytes so that it will return according to the size form the file.
Output: Hello
Also read: Capitalize first character of each sentence of a text file using Python
Leave a Reply