ReadIng From a text FIle
● To read a file, we need to open the file in one of the following modes: “r”, “r+”, “w+” or “a+” mode.
Once the file is opened then we can read data.
● There are three ways to read the contents of a file:
a) The read() method
b) The readline([n]) method
c) The readlines() method
The read() method::
● This method is used to read a specified number of bytes of data from a data file.
● If no argument or a negative number is specified in read(), the entire file content is read.
Syntax:
file_object.read(n)
Ex: Read 10 bytes from file
Here 10 bytes to be read from the file
Ex:Read the entire file
The readline([n]) method
● This method reads one complete line from a file where each line terminates with a newline (\n)
character.
● It can also be used to read a specified number (n) of bytes of data but maximum up to newline
character.
Ex1:
Here the readline() method reads 10 bytes from the specified file.
Ex2:
If no argument or a negative number is specified, it reads a complete line and returns string.
Looping/Iteration over a file object: To read the entire file line by line we can use loop. It will return an
empty string when an end of line (EOF) is reached.
The readlines() method:
● The method reads all the lines and returns the lines along with newline as a list of strings.
Ex1: To read data from a text file [Link] the readlines() method lines of the input file become
members of a list, where each list element ends with a newline character (‘\n’)