0% found this document useful (0 votes)
3 views2 pages

Chapter2 Read Function Notes

The document explains how to read from a text file using different modes and methods in Python. It details the use of the read(), readline(), and readlines() methods for reading file contents, including syntax and examples. Additionally, it mentions how to iterate over a file object to read it line by line.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Chapter2 Read Function Notes

The document explains how to read from a text file using different modes and methods in Python. It details the use of the read(), readline(), and readlines() methods for reading file contents, including syntax and examples. Additionally, it mentions how to iterate over a file object to read it line by line.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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’)

You might also like