in this post, I’ll show you Reading a file using deadline() python method. The readline()
is a built-in file method that helps read one complete line from the given file.
The built-in Python function readlines()
returns all lines in a file as a list, with each line being an item in the list object.
We’ll be following steps to read a file in python:
- We’ll open a file using
open()
function - The file object have
readline()
method to read content from text file. - Finally, Close the file using
close()
function.
Python read text file line by line
The following code help to read all content from the test.txt
file into a string.
Python file readlines() Example
The readline()
function takes a line from a file and returns it as a string. It accepts a hint parameter that indicates the maximum number of bytes/lines to read. It will return an empty string if the file’s end is reached.
The syntax:file.readlines(hint)
The hint
is an optional parameter and is used to limit the amount of lines returned. The default value is -1, which means all lines will be returned.
Sample file
Let’s have a sample file test.txt
. We’ll read this file using while loop:
Adam James Roy Ron
Let’s write python script to read above file using while loop:
# Using readline() file = open('test.txt', 'r') count = 0 while True: count += 1 # Get next line from file line = file.readline() # check end of file is reached if not line: break print("Line{}: {}".format(count, line.strip())) file.close()
Output:
Line1 Adam Line2 James Line3 Roy Line4 Ron
in the above code :
- We have opened
test.txt
file in read mode. - Read line by line file till end of file is reached.
- Close the file.